C 執行緒與函式的區域性變數
阿新 • • 發佈:2019-01-23
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <pthread.h> void* th_func(){ char c[100]; printf("c=%p, tid=%d\n", c, pthread_self()); return (void*)0; } void p(char* x[]){ printf("pppp=%d\n", sizeof(x)); } void c(int v, int d){ if(d>3) return; v+=v*d; printf("v=%p\n", &v); c(v,d+1); } int main(){ printf("int=%d, long=%d, long long=%d\n", sizeof(int), sizeof(long), sizeof(long long)); int i; printf("Test in main:\n----------------------------------------\n"); th_func(); th_func(); printf("Abort size of arr arr*\n----------------------------------------\n"); short ss[]={1,23,4,5,55,5,6,7}; char* xx[]={"sadl","da","22","dd","sd"}; printf("short=%d,char*=%d\n----------------------------------------\n", sizeof(ss), sizeof(xx)); p(xx); printf("String char action:\n----------------------------------------\n"); char *str="123456789"; if(str[1]>0) printf("%d > 0\n",str[1]); else printf("%d < 0\n",str[1]); char* x = "TO019"; printf("mah num=%d\n", atoi(x+4)); printf("----------------------------------------\n"); printf("Function call itself:\n----------------------------------------\n"); c(1,0); printf("Test in thread:\n----------------------------------------\n"); for(i=0;i<5;i++){ pthread_t tid; if(pthread_create(&tid, NULL, th_func, NULL)!=0) { printf(" pthread_create failed\n"); exit(1); } } sleep(3); return 0;}
結果:
int=4, long=8, long long=8 Test in main: ---------------------------------------- c=0x7ffc9df43fb0, tid=2116724480 c=0x7ffc9df43fb0, tid=2116724480 Abort size of arr arr* ---------------------------------------- short=16,char*=40 ---------------------------------------- pppp=8 String char action: ---------------------------------------- 50 > 0 mah num=9 ---------------------------------------- Function call itself: ---------------------------------------- v=0x7ffc9df4401c v=0x7ffc9df43ffc v=0x7ffc9df43fdc v=0x7ffc9df43fbc Test in thread: ---------------------------------------- c=0x7f1a7c4a4e40, tid=2085246720 c=0x7f1a7baa3e40, tid=2074756864 c=0x7f1a7cea5e40, tid=2095736576 c=0x7f1a7d8a6e40, tid=2106226432 c=0x7f1a7e2a7e40, tid=2116716288
結論:
在同一個執行緒反覆呼叫一個函式,其區域性變數使用同一個記憶體空間;
在不同執行緒呼叫一個函式、或函式多次遞迴呼叫自己,其區域性變數使用不同記憶體空間;
因此,執行緒安全要解決的是全域性變數、靜態變數。