我正在使用Linux
void *threadStart()
{
int threadClose;
led = 1;
delay(10);
led = 0;
pthread_exit(&threadClose);
}
main()
{
pthread_t thread1;
while(1)
{
pthread_create(&thread1,NULL,threadStart,NULL);
/* calling some function calls here */
}
}
这是我的C代码。当我编译它时,这将成功编译,当我运行此程序时,LED 有时会开始闪烁。LED 将停止闪烁,pthread_create()
函数返回错误。
我做错了什么或有什么建议吗?
创建线程时,它会消耗资源,例如线程堆栈的全局资源,通常是内存。
当胎面结束时,如果采取以下两个操作之一,则会释放这些资源
- 调用
pthread_join()
,传递线程的 ID。 - 线程已分离。这可以在使用
pthread_detach()
创建胎面后的任何时间完成,传递线程的ID。
您显示的代码不执行上述两个操作。
因此,创建这些线程的程序(在while
循环内(迟早会耗尽资源来创建任何新线程,因此pthread_create()
开始失败。