C线程和加入

我有一个关于C线程及其返回值的问题。 我的目标是找到起始编号和结束编号之间的所有素数。 我将有4个线程,每个线程执行四分之一的范围。

例如,1到100之间的素数。

  • 线程1找到1到25之间的素数
  • 线程2 26 – 50
  • 线程3 51 – 75
  • 线程4 76 – 100

所有素数都将存储在一个数组中,并且会有一个计算素数的函数。

我的问题是,当我加入线程时

pthread_join(tids[i], ptr); 

将ptr指向所有素数的组合数组,1 – 100?

这意味着我使用for循环来打印值

 printf("%d", ptr[i]); 

它会将所有素数从1 – 100打印成一个大arrays吗?

我加入了4个独立的arrays吗?

谢谢

phtread_join()将通过ptr返回相应的线程传递给pthread_exit()的内容 。 每个线程独立工作并计算自己的素数集,因此,每个线程应创建自己的数组,并且在所有线程连接后,您将打印每个数组的结果。 为了能够返回素数的结果集及其计数,我们必须使用自己的结构类型:

 struct comp_result { unsigned *p_arr; unsigned count; }; 

我将说明没有锁定的方式:

 compute_thread (...) { ... struct comp_result *p_res = malloc(sizeof(struct comp_result)); p_res->p_arr = NULL; p_res->count = 0; for (num = start; num < end; num++) { if (is_prime(num)) { p_res->count++; /// increment number of primes and expand our storage p_res->p_arr = realloc(p_res->p_arr, p_res->count*sizeof(int)); p_res->p_arr[p_res->count-1] = num; // save prime in result array } } // pass pointer to per-thread result data pthread_exit(p_res); } main () { .... // create threads .... for (i = 0; i < num_of_threads; i++) { struct comp_result *p_res; // retrieve and print array from i-thread pthread_join(tids[i], &p_res); for (num = 0; num < p_res->count; num++) { printf(" %d ", p_res->p_arr[num]); } free(p_res->p_arr); free(p_res); } } 

锁定的插图需要一个结构类型,因为我们将指向结果共享数据的指针传递到每个线程:

 struct control { unsigned start; unsigned end; struct comp_result *p_res; } compute_thread (ptr) { struct control *p_cont = (struct control*)ptr; // retrieve the pointer to shared, but be accurate with it! struct comp_result *p_res = p_cont->p_res; // initialize lock pthread_mutex_init(&p_res->lock, NULL); ... for (num = p_cont->start; num < p_cont->end; num++) { if (is_prime(num)) { pthread_mutex_lock(&p_control->lock); // modify shared data with locking p_res->count++; /// increment number of primes and expand our storage p_res->p_arr = realloc(p_res->p_arr, p_res->count*sizeof(int)); p_res->p_arr[p_res->count-1] = num; // save prime in result array pthread_mutex_unlock(&p_control->lock); } } pthread_exit(NULL); } main () { //create one shared data and initialize it: struct comp_result *p_res = malloc(sizeof(struct comp_result)); p_res->p_arr = NULL; p_res->count = 0; for (i = 0; i < num_of_threads; i++) { // create per-thread control data: struct control *p_control = malloc(sizeof(struct control)); p_control->start = p_control->end = p_control->p_res = p_res; pthread_crate(&tids[i], NULL, compute_thread, p_control); } .... for (i = 0; i < num_of_threads; i+++) { pthread_join(tids[i], NULL); } // now all threads are completed and we are ready to read result: for (num = 0; num < p_res->count; num++) { printf(" %d ", p_res->p_arr[num]); } }