I am trying multithreading in my C project, using pthread. I was playing with this code but it is getting crashed and don't know why.
#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%d
", *myid, n); // .... line 13
}
printf("Thread number: %d, Static: %d, Global: %d
", *myid, 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
", rc);
exit(-1);
}
//pthread_join(threads[c], NULL); // .... line 33
}
pthread_exit(NULL);
}
int main()
{
function();
}
1. If I delete line 13: printf("%d%d
", *myid, n);
it works properly.
I think every thread function have their own variable n and after some cycles they can access their own variable. So, why it crashed???
2. If I use line 33: pthread_join(threads[c], NULL);
,then it works but the thread works sequentially which I think perform slower.
Can someone suggest me a better approach to use faster multithreading .
question from:
https://stackoverflow.com/questions/65873601/pthread-getting-crashed-in-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…