pthread库基本示例无法正常工作

时间:2016-07-11 14:09:17

标签: c pointers pthreads

我在C上寻找pthread。所以我是新人。我试图在pthread代码中学习指针的语法和角色。任何人都可以告诉我,根据代码我的​​错误是什么?我无法理解清楚,我做了什么。

当我试图检查返回值pthread_create()时,我的错误/随机值。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int *f_1,*f_2,*f_3,*f_4;

void p1(void *a);
void p2(void *a);
void p3(void *a);
void p4(void *a);

int main(void){
pthread_t thread_1, thread_2, thread_3, thread_4;
int *x=1,*y=2,*z=3,*w=4;

f_1=pthread_create(&thread_1, NULL, p1,(void *)x);
f_2=pthread_create(&thread_2, NULL, p2,(void *) y);
f_3=pthread_create(&thread_3, NULL, p1,(void *) z);
f_4=pthread_create(&thread_4, NULL, p1,(void *) w);

pthread_join(thread_1,NULL);
pthread_join(thread_2,NULL);
pthread_join(thread_3,NULL);
pthread_join(thread_4,NULL);


printf("Hi! From %d. thread!",f_1);
printf("Hi! From %d. thread!",f_2);
printf("Hi! From %d. thread!",f_3);
printf("Hi! From %d. thread!",f_4);

return 0;
}
void p1(void *a){
f_1=(int *)a;
}

void p2(void *a){
f_2=(int *)a;
}

void p3(void *a){
f_3=(int *)a;
}

void p4(void *a){
f_4=(int *)a;
}

2 个答案:

答案 0 :(得分:0)

pthread_create()返回int,您试图将其存储在int *(指针)中。这是实现定义的行为。

f_1=pthread_create(&thread_1, NULL, p1,(void *)x);
f_2=pthread_create(&thread_2, NULL, p2,(void *) y);
f_3=pthread_create(&thread_3, NULL, p1,(void *) z);
f_4=pthread_create(&thread_4, NULL, p1,(void *) w);

接下来,您正在使用%d打印指针

printf("Hi! From %d. thread!",f_1);
printf("Hi! From %d. thread!",f_2);
printf("Hi! From %d. thread!",f_3);
printf("Hi! From %d. thread!",f_4);

调用undefined behavior

要解决上述两个问题,您的所有f_n变量都应为int类型,而非int * s。

那就是说,线程函数的函数原型是

void *(*start_routine) (void *)

这是一个返回void *并接受void *的函数。您可能希望根据该更改函数签名和线程函数的定义。

答案 1 :(得分:0)

我认为你的线程函数应该是指向void的指针,例如:

void *p1(void *arg);
void *p2(void *arg);

https://computing.llnl.gov/tutorials/pthreads/man/pthread_create.txt

在此处查找“示例:Pthread创建和终止” https://computing.llnl.gov/tutorials/pthreads/