#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string. h> #include <pthread. h> char message[50]="Hello World"; void *thread_function(void *arg) { printf("=-=CHILD run and want to sleep(5). message NOW is %s \n", (char *Jarg); sleep(5); strcpy(message, "HELLO FATHER!"]; fatheV pthread_ exit("=== Thank you for your CPU time!"); } int main() { int res; pthread_t threadCH void thread_ resulty res=pthread create(&threadCH, NULL, thread_function, (void' "]message); 仓 if (res!=0) { perror("Thread creation failed!"); exit(EXIT_FAILURE); } printf("MAIN THREAD is Waiting for thread to finish by JOIN. . . \n"]; res=pthread_join(threadCH, &thread_ result); if(res!=0) { perror("Thread join failed! \n"); exit(EXIT_FAILURE); } printf("CHILD THREAD returned %s \n", (char*)thread_result); printf("Message NOW is %s \n", message); exit(EXIT_FAILURE); }
时间: 2024-04-28 14:26:57 浏览: 164
用c语言实现的逆序文本程序
这段代码是一个使用pthread库创建线程的例子,主函数中调用pthread_create函数创建了一个子线程,并将一个字符串指针作为参数传递给子线程。子线程执行thread_function函数,在打印一条信息后,调用了sleep函数暂停了5秒钟,然后将message字符串的值改为"HELLO FATHER!",最后调用pthread_exit函数结束了子线程的执行。
在主函数中,使用pthread_join函数等待子线程结束,并获取子线程的返回值。最后打印出子线程的返回值和message字符串的值。
阅读全文