我已经编写了这段代码来理解局部变量如何在一个线程中工作。我从另一个线程创建它时将局部变量的地址传递给线程。一旦原始线程退出,局部变量也会被破坏,因为堆栈帧被销毁。那么在新线程中会发生什么?为什么没有分段错误?C pthreads传递局部变量
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
pthread_t t1,t2;
pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
void* thr_fun2(void *p);
void* thr_fun1(void *p)
{
int data = 0;
sleep(1);
pthread_create(&t2,0,thr_fun2,&data);
printf("Thread 1 entered....\n");
while(1)
{
pthread_mutex_lock(&mtx);
if(data > 5)
pthread_exit(0);
printf("thread1:data =%d\n ",data);
data++;
sleep(1);
printf("thread1:data(inc) =%d\n ",data);
pthread_mutex_unlock(&mtx);
sleep(1);
}
}
void* thr_fun2(void *p)
{
sleep(1);
printf("Thread 2 entered....\n");
while(*(int *)p < 10)
{
pthread_mutex_lock(&mtx);
printf("thread2:data =%d\n ",*(int *)p);
(*(int *)p)++;
sleep(1);
printf("thread2:data(inc) =%d\n ",*(int *)p);
pthread_mutex_unlock(&mtx);
sleep(1);
}
}
main()
{
pthread_mutex_init(&mtx,0);
pthread_create(&t1,0,thr_fun1,0);
pthread_join(t1,0);
pthread_join(t2,0);
// printf("Back in main fun \n");
pthread_mutex_destroy(&mtx);
pthread_exit(0);
}
输出:
Thread 1 entered....
thread1:data =0
thread1:data(inc) =1
Thread 2 entered....
thread2:data =1
thread2:data(inc) =2
thread1:data =2
thread1:data(inc) =3
thread2:data =3
thread2:data(inc) =4
thread1:data =4
thread1:data(inc) =5
thread2:data =5
thread2:data(inc) =6
未定义的行为... –
另外,请确保't1'在thread2的输出进入之前已加入? –
仅仅因为代码错了并不意味着它不得不崩溃。它可能会崩溃;它不必崩溃。你可以得到各种形式的微妙或不那么微妙的腐败。 –