我已經編寫了這段代碼來理解局部變量如何在一個線程中工作。我從另一個線程創建它時將局部變量的地址傳遞給線程。一旦原始線程退出,局部變量也會被破壞,因爲堆棧幀被銷燬。那麼在新線程中會發生什麼?爲什麼沒有分段錯誤?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的輸出進入之前已加入? –
僅僅因爲代碼錯了並不意味着它不得不崩潰。它可能會崩潰;它不必崩潰。你可以得到各種形式的微妙或不那麼微妙的腐敗。 –