- 论坛徽章:
- 1
|
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <sys/syscall.h>
- pid_t gettid()
- {
- pid_t tid;
- tid = syscall(SYS_gettid);
- return tid;
- }
- class B
- {
- public :
- int data;
- B()
- {
- data = 100;
- }
- static void* print(void* __this)
- {
- B * _this =(B *)__this;
- while (1) {
- printf("print pid=%d, tid=%d, data=%d\n", getpid(), gettid(), _this->data);
- sleep(1);
- }
- pthread_exit(NULL);
- }
- static void* add(void* __this)
- {
- B * _this =(B *)__this;
- while (1) {
- _this->data += 1;
- printf("add pid=%d, tid=%d, data=%d\n", getpid(), gettid(), _this->data);
- sleep(2);
- }
- pthread_exit(NULL);
- }
- void start_thread()
- {
- pthread_t thread_add, thread_print;
- pthread_create(&(thread_print), NULL, print, (void*)this);
- pthread_create(&(thread_add), NULL, add, (void*)this);
- }
- };
- int main(int argc, char* argv[])
- {
- B b;
- b.start_thread();
- while(1) {
- printf("main pid=%d, tid=%d, data=%d\n", getpid(), gettid(), b.data);
- sleep(3);
- }
- return 0;
- }
复制代码
我了解是 thread 在 stack 宣告的變量都是每個 thread 各自獨立
只有是 global 變量屬於 .data 跟 heap 是 process 裡面所有thread 共享
那我疑問是在上面網址程式裡面 main() 函數宣告一個 B class 的 instance b 變量
那這塊instace 應該是屬於 stack 不是 heap(因為我不是new 出來的)
那我之後呼叫 b.start_thread();
產生兩條thread 在 member function add / print 還有 main 函數都用 while(1)
不斷印出data 跟 pid & tid , 看起來 class 的 data變量 是共享的~
那我不懂是 B b; 宣告出來的 b 應該屬於 stack ,
在同Process 底下的不同 thread 怎麼能夠存取在 stack instace ?
謝謝
|
|