c - 在 C 编程中如何创建一个线程来创建另一个线程?

标签 c multithreading

我在线程中创建线程时遇到问题。我需要创建 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/

相关文章:

objective-c - %qx 格式说明符是什么意思

java - ArrayList 可以在多线程环境中用于只读目的吗?

c++ - Node JS native 模块 : Can You Run C/C++ Methods In A Separate Libuv/NodeJS Style Process?

python - 如何管理数据库连接,尤其是在多线程的情况下

Python 并行线程

spring - spring executor中java executor framework的invokeAll等价方法

c - UART 接收中断启用但没有 ISR?

c - else if 条件没有正确执行

c - 通过自定义排序/删除链接列表中的重复项来跳过最后一项

cuBlas、cuda 功能不起作用,没有产生错误