gpt4 book ai didi

无法将值传递给 C 中的线程

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:18 24 4
gpt4 key购买 nike

我是线程主题的新手,我想创建一些进程和线程。但是我无法将我的值传递给线程。

请让我知道我的代码有什么问题。

编译时出现以下错误:

warning: passing argument 2 of ‘pthread_create’ makes pointer from integer without a cast [-Wint-conversion]

这是我的代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <pthread.h>
///////////////////////////

void *print_fun(int *id) {

printf("Thread #%d is using the print function now! \n",a);
}

int main()
{
int pid1,pid2,pid3;
pthread_t t1,t2;

pid1=fork();
if (pid1==0)
{//child #1
pthread_create(&t1,1,print_fun,NULL);
printf("The child of process #1 has been created!!\n");
}
if (pid1>0)
{//Father #1
printf("The process #1 has been created!!\n");
pid2=fork();
if (pid2>0)//Father #2
{
printf("The process #2 has been created!!\n");
pid3=fork();
if (pid3>0)//Father #3
{
printf("The process #3 has been created!!\n");
}
else
{
printf("There is error in the third fork!\n");
}
}
else if(pid2==0)//child #2
{
pthread_create(&t1,2,print_fun,NULL);
printf("The child of process #2 has been created!!\n");
}
else
{
printf("There is error in the second fork!\n");
}
}
else
{//error
printf("There is error in the first fork!\n");
}

pthread_exit(NULL);
}

最佳答案

你可能想要这个:

pthread_create(&t1, NULL, print_fun, (void*)2);

代替:

pthread_create(&t1, 2, print_fun, NULL);

pthread_create 的第二个参数是指向 pthread_attr_t 结构或 NULL 的指针。

关于无法将值传递给 C 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41143390/

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