理解執行緒的小程式

2022-08-05 11:00:24 字數 1396 閱讀 5268

在看《beginning linux programming》時,為了更好的理解執行緒的概念,書中列舉了這樣乙個小例子:

#include #include #include #include #include void *thread_function(void *arg);

char message = "hello world";

int main()

printf("waiting for thread to finish...\n");

res = pthread_join(a_thread, &thread_result);

if (res != 0)

printf("thread joined, it returned %s\n", (char *)thread_result);

printf("message is now %s\n", message);

exit(exit_success);

}void *thread_function(void *arg)

將程式編譯鏈結後執行,可以看到下面這樣的結果

➜  chapter12 ./thread

waiting for thread to finish...

thread_function is running, argument was hello world

thread joined, it returned thank you for the cpu time

message is now bye!

這裡使用pthread_create建立新執行緒,pthread_create的定義如下:

#include int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
根據pthread_create要求,thread_function只有乙個指向void的指標作為引數,返回的也是指向void的指標。

當建立新的執行緒後,新執行緒在thread_function中開始執行,列印自己的引數。

原有執行緒在確保新執行緒啟動後呼叫pthread_join函式等到執行緒結束,並且將新執行緒的返回值存在thread_result指標裡。

新執行緒可以直接訪問message陣列變數,如果是呼叫fork()的話就沒有這種效果。

不由感慨,如果不多懂一些c語言,那麼很難提高自己python水平啊。

C小程式 fork理解

include include include int main void return 0 1.總共生成了幾個程序?答 4個。可以在return 0 之前加乙個sleep 100 然後通過 pstree p grep fork檢視 pstree p grep fork bash 14207 for...

微信小程式 rpx單位的理解

如何理解rpx?rpx responsive pixel 可以根據螢幕寬度進行自適應。規定螢幕寬為750rpx。如在 iphone6 上,螢幕寬度為375px,共有750個物理畫素,則750rpx 375px 750物理畫素,1rpx 0.5px 1物理畫素。小測試 1 rpx 全稱是什麼?請填寫英...

程式媛小琦 理解的作用域

1 全域性作用域 全域性作用域中定義的變數和方法都會被繫結到window上 除了let const var a 1 全域性變數 function fnscope 2 塊級作用域 包裹的就是塊級作用域 es6新增的let const定義的 console.log a 找不到 出了塊級作用域訪問不到a了...