线程通信的两个方法_c语言基础知识总结大全

线程通信的两个方法_c语言基础知识总结大全C语言面试常见问题总结-线程间通信的三种方法以下是使用C语言的多线程计算-之间的质数的示例代码:“`c#include <stdio.h>#inclu

C语言面试常见问题总结—线程间通信的三种方法   以下是使用C语言的多线程计算-之间的质数的示例代码: “`c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 4 #define RANGE_START #define RANGE_END // 定义线程参数结构体 typedef struct { int start; int end; int *count; } thread_args; // 判断一个数是否为质数 int is_prime(int num) { int i; if (num <= 1) { return 0; } for (i = 2; i*i <= num; i++) { if (num % i == 0) { return 0; } } return 1; } // 线程函数 void *thread_func(void *args) { int i, count = 0; thread_args *thread_args = (thread_args *)args; for (i = thread_args->start; i <= thread_args->end; i++) { if (is_prime(i)) { count++; } } *(thread_args->count) += count; pthread_exit(NULL); } int main() { int i, count = 0; pthread_t threads[NUM_THREADS]; thread_args args[NUM_THREADS]; // 分配线程任务 for (i = 0; i < NUM_THREADS; i++) { args[i].start = RANGE_START + i*(RANGE_END-RANGE_START)/NUM_THREADS; args[i].end = RANGE_START + (i+1)*(RANGE_END-RANGE_START)/NUM_THREADS – 1; args[i].count = &count; pthread_create(&threads[i], NULL, thread_func, (void *)&args[i]); } // 等待线程结束 for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf(“Number of primes between %d and %d is %d   ”, RANGE_START, RANGE_END, count); return 0; } “` 代码中使用了4个线程来计算,可以根据需要调整`NUM_THREADS`的值。线程函数`thread_func`中计算每个线程分配到的范围内的质数数量,并将结果累加到`count`变量中。最终输出计算结果。

2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/72736.html

(0)
上一篇 2024年 8月 6日
下一篇 2024年 8月 6日

相关推荐

关注微信