gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:38:21 25 4
gpt4 key购买 nike

我正在寻找 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;
}

最佳答案

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。

也就是说,线程函数的函数原型(prototype)是

void *(*start_routine) (void *)

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

关于c - pthread 库基本示例无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com