进程主线程与子线程执行顺序控制
#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 *)arg);
sleep(5);
strcpy(message, "HELLO FATHER!"); //对全局变量message进行修改/重负值
pthread_exit("===Thank you for your CPU time!"); //终止线程
}
int main() {
int res;
pthread_t threadCH; //即将要创建的子线程的名字
void *thread_result; //将要保存子线程的返回结果
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);
}//main
/*
gcc 5-11mythread.c -l pthread
./a.out
MAIN THREAD is Waiting for thread to finish by JOIN...
===CHILD run and want to sleep(5). message NOW is Hello World
此处等待5秒
CHILD THREAD returned ===Thank you for your CPU time!
Message NOW is HELLO FATHER!
*/
线程即要共享资源,也要有序使用;
join控制子线程写后主线程读