pthread线程创建用法实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int main()
{
int res;
pthread_t thread_1;
void *thread_result;
res = pthread_create(&thread_1, NULL, thread_function, (void *)message);//创建线程,参数为message
if (res != 0) {
perror("thread creation failed");
exit(-1); //exit(EXIT_FAILURE);
}
printf("Message is %s\n",message);
printf("Waiting for thread to finish...\n");
res = pthread_join(thread_1, &thread_result); //等待线程结束,并将返回的结果放到thread_result中
if (res != 0) {
perror("thread join failed");
exit(-1);
}
printf("Thread joined, return %s, Message is changed to %s\n", (char *)thread_result, message);//message被线程改变
exit(0);
}
void *thread_function(void *arg)
{
printf("thread_function is running. Argument is %s\n", (char *)arg);
sleep(2);//线程等待2s
strcpy(message, "Bye!");//与主线程共享数据message,所以可以改变message的值
pthread_exit("Thank you for the CPU time");//返回字符串给thread_result
}
GCC下运行结果:
[root@SW4-SW one C]# gcc -o thread1 thread1.c -lpthread
thread1.c: In function ‘thread_function’:
thread1.c:35: warning: incompatible implicit declaration of built-in function ‘strcpy’[root@SW4-SW one C]#
[root@SW4-SW one C]#
[root@SW4-SW one C]# ./thread1
Message is Hello World
thread_function is running. Argument is Hello World
Waiting for thread to finish...
Thread joined, return Thank you for the CPU time, Message is changed to Bye!
[root@SW4-SW one C]#。