2017-07-18 77 views
0

我已經編寫了這段代碼來理解局部變量如何在一個線程中工作。我從另一個線程創建它時將局部變量的地址傳遞給線程。一旦原始線程退出,局部變量也會被破壞,因爲堆棧幀被銷燬。那麼在新線程中會發生什麼?爲什麼沒有分段錯誤?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 
+1

未定義的行爲... –

+0

另外,請確保't1'在thread2的輸出進入之前已加入? –

+1

僅僅因爲代碼錯了並不意味着它不得不崩潰。它可能會崩潰;它不必崩潰。你可以得到各種形式的微妙或不那麼微妙的腐敗。 –

回答

0

這是不確定的行爲。這是與glibc?通常沒有分段錯誤,因爲glibc保留了線程堆棧的緩存,所以線程退出後內存不會立即釋放。

+0

是glibc。緩存直到程序終止? –

+0

@Sreena_th_read,當然不是系統的,如果一個程序的行爲是未定義的,基本上都會發生任何事情,尤其是程序可能不會報告所有測試的錯誤,然後關閉硬盤 –

+0

@Sreena_th_read,線程堆棧緩存的大小是固定的,堆棧可以重新用於新的線程,如果創建並終止更多的線程,它可以被釋放。 –

0

當data == 6時,thread1退出但不解鎖互斥鎖。 線程2保持阻塞狀態,等待鎖定互斥鎖。 所以它沒有seg-fault。它只是陷入僵局。

+0

嗨,我將它改爲: 如果(數據> 5) pthread_mutex_unl { ock(&mtx); pthread_exit(0); } 仍然是相同的輸出。 –