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

pthread library basic example does not work properly

我正在寻找 C 上的 pthread。所以我是新手。我正在尝试学习 pthread 代码中指针的语法和角色。谁能告诉我,根据代码我的​​错误是什么?我无法清楚地理解,我做了什么。

当我尝试检查 return 值时 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;
}

pthread_create() returns 一个 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 * 的函数。您可能希望根据它更改线程函数的函数签名和定义。

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

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

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

在这里寻找"Example: Pthread Creation and Termination" https://computing.llnl.gov/tutorials/pthreads/