在 C 语言的后台运行线程
running threads in background in c
我用pthread_create创建了5个线程。我想在后台运行这些线程,所以我没有加入这些线程。但是该程序正在产生奇怪的输出。这些原因可能是什么?
程序:
for(i = 0; i < 5; i++)
{
pthread_create(&thread[i], NULL, func, &i)
}
一个可能的原因可能是您将指向i
的指针作为参数传递给线程,并且该指针对于所有线程都是相同的。因此,在循环之后,将为所有线程5
i
。
您可以使用正确的类型转换将实际值作为指针传递,而不是传递指针:
pthread_create(&thread[i], NULL, func, (void *) i);
在线程函数中:
void *func(void *thread_argument)
{
int i = (int) thread_argument;
/* ... */
}
相关文章:
- 使用基类中的派生方法运行线程,而无需使用模板
- 使用 ubuntu 终端在 c++ 上运行线程类的问题
- 将项目添加到队列时运行线程
- 运行线程和线程对象之间的关系
- 在 gtest 中运行线程
- 是否有一种可接受的运行线程或按顺序执行的方法
- 从类中运行线程
- 如何在第三方函数调用之前同时运行线程
- 在优先级最低的核心中运行线程
- 在C++中并行运行线程
- 在C 11中的背景中运行线程
- 在运行线程中处理事件
- 使用对象生存期运行线程
- WINAPI CreateThread并不总是运行线程
- 树莓派与 c++ 运行线程,在网络上发布数据
- 使用变量类型 std::function 运行线程
- Eclipse CDT 多线程调试不是最佳的 - 如何以独占方式运行线程
- 在 C 语言的后台运行线程
- 正在运行线程
- 在远程计算机上运行线程