日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

线程运行程序c语言,理解线程1 C语言示例的程序

發(fā)布時(shí)間:2025/4/5 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程运行程序c语言,理解线程1 C语言示例的程序 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一個(gè)簡(jiǎn)單的C語(yǔ)言實(shí)現(xiàn)的線(xiàn)程示例

在看《Beginning Linux Programming》時(shí),為了更好的理解線(xiàn)程的概念,書(shū)中列舉了這樣一個(gè)小例子:

#include

#include

#include

#include

#include

void *thread_function(void *arg);

char message[] = "Hello World";

int main() {

int res;

pthread_t a_thread;

void *thread_result;

res = pthread_create(&a_thread, NULL, thread_function, (void *)message);

if (res != 0) {

perror("Thread creation failed");

exit(EXIT_FAILURE);

}

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

res = pthread_join(a_thread, &thread_result);

if (res != 0) {

perror("thread join failed");

exit(EXIT_FAILURE);

}

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) {

printf("thread_function is running, Argument was %s\n", (char *)arg);

sleep(3);

strcpy(message, "Bye!");

pthread_exit("Thank you for the CPU time");

}

將程序編譯鏈接后運(yùn)行,可以看到下面這樣的結(jié)果

? 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 創(chuàng)建新線(xiàn)程, pthread_create 的定義如下:

#include

int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

根據(jù) pthread_create 要求, thread_function 只有一個(gè)指向void的指針作為參數(shù),返回的也是指向void的指針。

當(dāng)創(chuàng)建新的線(xiàn)程后,新線(xiàn)程在 thread_function 中開(kāi)始執(zhí)行,打印自己的參數(shù)。

原有線(xiàn)程在確保新線(xiàn)程啟動(dòng)后調(diào)用 pthread_join 函數(shù)等到線(xiàn)程結(jié)束,并且將新線(xiàn)程的返回值存在 thread_result 指針里。

新線(xiàn)程可以直接訪(fǎng)問(wèn) message 數(shù)組變量,如果是調(diào)用 fork() 的話(huà)就沒(méi)有這種效果。

python也提供了處理線(xiàn)程相關(guān)的 thread 和 基于它上面抽象的 threading 等模塊,將在以后的文章中探究。

不由感慨,如果不多懂一些C語(yǔ)言,那么很難提高自己Python水平啊。

總結(jié)

以上是生活随笔為你收集整理的线程运行程序c语言,理解线程1 C语言示例的程序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。