我在线程中创建线程时遇到问题。我需要创建 thread1 和 thread1 做“某事”以及创建将做其他事情的 thread2。
我的代码:
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
void *msg1(void *ignored)
{
void *msg2(void *ignored)
{
printf("this is thread2");
}
pthread_t thread;
int thread2;
thread2 = pthread_create(&thread, NULL, msg2, NULL);
return 0;
}
int main ()
{
pthread_t thread;
int thread1;
thread1 = pthread_create(&thread, NULL, msg1, NULL);
return 1;
}
最佳答案
从线程回调中创建线程与从主线程中创建它们没有什么不同。自然地,每个线程都需要自己的回调函数——它是用 pthreads 的给定格式声明的,void* func (void*)
。
出于未知原因,您尝试在另一个函数内声明一个函数。这没有任何意义,在 C 语言中是不允许的。线程或没有线程。
如果您希望限制第二个线程的范围,则将两个线程回调放在它们自己的模块中,并使第二个回调函数静态
。这是非常基础的程序设计 - 我建议在开始使用多线程之前先研究一下。
关于c - 在 C 编程中如何创建一个线程来创建另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39632917/