【问题标题】:pthread library basic example does not work properly [closed]pthread 库基本示例无法正常工作 [关闭]
【发布时间】:2016-07-11 14:09:17
【问题描述】:

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

【问题讨论】:

  • I cant understand clearly, what i did.... 问:那是怎么做到的?
  • 您能否至少解释一下您尝试做什么,以及您在使用此代码时遇到了哪些具体问题?
  • 来自一些网站,但没有编译。
  • 为什么这段代码没有运行?问题是这个。
  • 我已经编辑了问题(根据我的回答收到的回复),如果我弄坏了东西,请回复。

标签: c pointers pthreads


【解决方案1】:

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 * 的函数。您可能希望根据此更改线程函数的函数签名和定义。

【讨论】:

  • 你这么说,我不能用 pthread_create() 从子函数返回值?
  • @outSider 我说的是pthread_create()函数调用本身的返回值,请查看链接的手册页。
  • 好的,我现在试试。
【解决方案2】:

我认为你的线程函数应该是指向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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2017-04-08
    • 1970-01-01
    • 2016-04-28
    • 2016-02-25
    • 1970-01-01
    相关资源
    最近更新 更多