Abh*_*nty 1 c pthreads pthread-join
我是并行编程领域的新手,所以我决定摆弄pthread_join()子程序.我想出了以下代码来计算*X + Y,其中a是标量,X,Y是某种大小的向量.
这是我写的:
#include <pthread.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
#define VECTOR_SIZE 65
struct DAXPYdata
{
/* data */
long a;
long X[VECTOR_SIZE];
long Y[VECTOR_SIZE];
};
struct DAXPYdata daxpystr;
void *calcDAXPY(void *);
int main(int argc, char *argv[])
{
int vec_index;
/*Initialize vectors X and Y an scalar a*/
daxpystr.a = 57;
for(vec_index = 0 ; vec_index < 65 ; vec_index++){
daxpystr.X[vec_index] = vec_index + 1;
daxpystr.Y[vec_index] = vec_index + 2;
}
pthread_t call_thread[NUM_THREADS];
pthread_attr_t attr;
int flag;
long i;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0;i < NUM_THREADS;i++){
printf("In main() : Creating thread %ld \n", i);
flag = pthread_create(&(call_thread[i]), &attr, calcDAXPY, (void *)i);
if(flag == 0){
printf("ERROR; return code from pthread_create() is %d\n", flag);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i = 0; i < NUM_THREADS ; i++) {
flag = pthread_join(call_thread[i], &status);
if (flag) {
printf("ERROR; return code from pthread_join() is %d\n", flag);
exit(-1);
}
printf("main(): Completed join with thread %ld having a status of %ld\n", i, (long)status );
}
/* code */
printf("main(): Program completed, exiting!\n");
pthread_exit(NULL);
}
void *calcDAXPY(void *thread_id)
{
int i;
long tid;
tid = (long)thread_id;
printf("Thread %ld starting execution\n", tid);
for(i = 0 ; i < VECTOR_SIZE ; i++){
daxpystr.X[i] = daxpystr.a*daxpystr.X[i] + daxpystr.Y[i];
}
printf("Result of a*X + Y : ");
for (i = 0; i < VECTOR_SIZE ; i++)
{
printf("%ld ", daxpystr.X[i]);
}
pthread_exit((void *)thread_id);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在pthread_create()子例程上抛出一个错误,从而导致单个线程执行.以下是输出
In main() : Creating thread 0
ERROR; return code from pthread_create() is 0
Thread 0 starting execution
Result of a*X + Y : 59 117 175 233 291 349 407 465 523 581 639 697 755 813 871 929 987 1045 1103 1161 1219 1277 1335 1393 1451 1509 1567 1625 1683 1741 1799 1857 1915 1973 2031 2089 2147 2205 2263 2321 2379 2437 2495 2553 2611 2669 2727 2785 2843 2901 2959 3017 3075 3133 3191 3249 3307 3365 3423 3481 3539 3597 3655 3713 3771 logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]
Run Code Online (Sandbox Code Playgroud)
有关如何解决这个问题的任何想法?
成功时,pthread_create()返回0
所以线程运行,只是错误代码检查应该像反过来一样:
if(flag != 0){
printf("ERROR; return code from pthread_create() is %d\n", flag);
exit(-1);
}
Run Code Online (Sandbox Code Playgroud)