c,#include,#include,#include,,#define NUM_THREADS 4,#define TASKS 10,,void *worker(void *arg) {, int id = *((int *)arg);, for (int i = 0; i< TASKS / NUM_THREADS; i++) {, printf("Thread %d is processing task %d\n", id, i + 1);, }, return NULL;,},,int main() {, pthread_t threads[NUM_THREADS];, int thread_ids[NUM_THREADS];,, for (int i = 0; i< NUM_THREADS; i++) {, thread_ids[i] = i;, if (pthread_create(&threads[i], NULL, worker, &thread_ids[i]) != 0) {, perror("Failed to create thread");, exit(EXIT_FAILURE);, }, },, for (int i = 0; i< NUM_THREADS; i++) {, pthread_join(threads[i], NULL);, },, return 0;,},
``,,这段代码创建了四个线程,每个线程处理一部分任务,从而实现简单的负载均衡。Powered By Z-BlogPHP 1.7.3
Copyright Your WebSite.Some Rights Reserved.