如何解决pthread 在 C 中崩溃
我正在使用 pthread 在我的 C 项目中尝试多线程。我正在玩这个代码,但它崩溃了,不知道为什么。
#include <stdio.h>
#include <pthread.h>
int g = 0;
void *myThreadFun(void *vargp)
{
int *myid = (int *)vargp;
static int s = 0;
for(int n=0;n<1000;n++)
{
printf("%d\t%d\n",*myid,n); // .... line 13
}
printf("Thread number: %d,Static: %d,Global: %d\n",s,g);
++s; ++g;
}
void function()
{
int noa=10;
pthread_t threads[noa];
int rc;
for(int c=0;c<noa;c++)
{
rc = pthread_create(&threads[c],NULL,myThreadFun,(void *)&threads[c]);
if (rc) {
printf("Error:unable to create thread,%d\n",rc);
exit(-1);
}
//pthread_join(threads[c],NULL); // .... line 33
}
pthread_exit(NULL);
}
int main()
{
function();
}
1.如果我删除第 13 行:printf("%d\t%d\n",n);
它可以正常工作。
我认为每个线程函数都有自己的变量 n 并且经过一些循环后,他们可以访问自己的变量。那么,为什么它崩溃了???
2. 如果我使用第 33 行: pthread_join(threads[c],NULL);
,那么它可以工作,但线程按顺序工作,我认为执行速度较慢。
有人可以建议我使用更快的多线程的更好方法吗。
解决方法
当您的 main() 退出时,其他线程仍在运行并使用来自 main() 堆栈帧的实时变量 (*thr == &threads[c])。这些引用的操作高度依赖于您的运行时间和任意时间。所以首先:
for(int c=0;c<noa;c++)
{
rc = pthread_create(&threads[c],NULL,myThreadFun,(void *)&threads[c]);
if (rc) {
printf("Error:unable to create thread,%d\n",rc);
exit(1);
}
}
for(int c=0;c<noa;c++)
{
rc = pthread_join(threads[c],NULL);
if (rc) {
printf("Error:unable to join thread %d,c,rc);
exit(1);
}
}
现在你的线程都并行运行,只有当它们都完成时,main 才会退出,因此线程数组将保持活动状态,直到对它的所有引用都死了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。