1、gcc编译时不要忘了后面加-lpthread 如:cc test.c -lpthread
/*
============================================================================
Name : Test.c
Author : wangchuan
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
//不要忘了后面加 -lpthread
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
char message[]="THREAD_TEST";
void *thread_function(void *arg)
{
printf("线程在运行,参数为:%s\n",(char *)arg);
sleep(3);
strcpy(message,"线程修改");
pthread_exit("线程执行完毕");
}
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("线程创建失败");
exit(EXIT_FAILURE);
}
printf("等待线程结束...\n");
res=pthread_join(a_thread,&thread_result);
if(res!=0){
perror("等待线程结束失败");
exit(EXIT_FAILURE);
}
printf("线程已结束,返回值:%s\n",(char *)thread_result);
printf("Message的值为:%s\n",message);
exit(EXIT_SUCCESS);
return 0;
}