Linux多线程的问题
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
//#include<errno.h>
//#include<unistd.h>
int g_Flag = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * thread1(void *);
void * thread2(void *);
int main()
{
pthread_t * tid1;
pthread_t * tid2;
// int rc1=0;
// int rc2=0;
printf("main thread\n");
pthread_create(tid2, NULL, thread2, NULL);
// rc2=pthread_create(tid2, NULL, thread2, NULL);
// if(rc2 != 0)
//printf("%s:%d\n",__func__,strerror(rc2));
pthread_create(tid1, NULL, thread1, tid2);
// rc1=pthread_create(tid1, NULL, thread1, tid2);
// if(rc1 != 0)
//printf("%s:%d\n",__func__,strerror(rc1));
pthread_cond_wait(&cond,&mutex);
printf("main thread exit\n");
exit(0);
}
void * thread1(void * arg)
{
printf("this is thread1\n");
pthread_mutex_lock(&mutex);
if(g_Flag ==2)
pthread_cond_signal(&cond);
g_Flag = 1;
pthread_mutex_unlock(&mutex);
pthread_join(*(pthread_t*)arg,NULL);
pthread_exit(0);
}
void * thread2(void * arg)
{
printf("this is thread2\n");
pthread_mutex_lock(&mutex);
if(g_Flag ==1)
pthread_cond_signal(&cond);
g_Flag = 2;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
这段代码编译过了,但是执行的时候会出错,在第一个创建线程的时候就segment fault了。
但是,如果把
int rc1 = 0;
int rc2 = 0;
这两句加上,程序就能正常执行。
不明白这其中的问题,求解答
[解决办法]
改成 pthread_t tid1;
后面用 &tid1其他的一样改