libuv的线程池使用代码
时间: 2024-03-18 07:20:01 浏览: 210
线程池代码
以下是使用libuv的线程池的示例代码:
```c
#include <uv.h>
#include <stdio.h>
#define NUM_THREADS 4
void task(void* arg) {
int* num = (int*)arg;
printf("Thread %lu: %d\n", uv_thread_self(), *num);
}
int main() {
uv_thread_t threads[NUM_THREADS];
uv_threadpool_t pool;
// Initialize thread pool
uv_threadpool_create(&pool, NUM_THREADS);
// Add tasks to thread pool
for (int i = 0; i < 10; i++) {
int* num = malloc(sizeof(int));
*num = i;
uv_threadpool_work(&pool, task, num);
}
// Wait for tasks to complete
uv_threadpool_wait(&pool);
// Destroy thread pool
uv_threadpool_destroy(&pool);
return 0;
}
```
该示例创建了一个线程池,添加了10个任务,并等待它们完成。任务函数将打印线程ID和任务参数。
阅读全文