OS - 线程
一、什么是线程?
线程是一个进程内部的一个控制序列。
当进程执行fork调用时,将创建出该进程的一份副本。这个新进程拥有自己的变量和自己的PID,它的时间调度也是独立的,
它的执行几乎完全独立于父进程。
当进程创建一个新线程时,新的执行线程将拥有自己的栈(因此也有自己的局部变量),便与它的创建者共享全局变量、文件描述符、
信号处理函数和当前目录状态。
1. 创建一个线程 pthread_create 函数
#include <pthread.h> int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
成功返回0, 失败返回-1
第一个参数: 指向pthread_t 的一个指针,会写入这个线程的标识符
第二个参数: 线程属性
第三个参数: 线程启动要执行的函数
第四个参数: 传递给该函数的参数
2. pthread_exit 函数终止执行
#include <pthread.h> void pthread_exit(void *retval);
3. pthread_join 函数 等价于进程中wait
#inclue <pthread.h> int pthread_join(pthread_t th, void **thread_return);
成功返回0, 失败返回-1
第一个参数:指定将要等待的线程
第二个参数:指针,指向线程的返回值
一个最简单的线程程序
// 线程修改了全局变量
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> 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); } // 创建线程函数 将message改成Bye! 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"); } /* gcc -D_REENTRANT thread.c -o thread -lpthread [root@localhost ~]# ./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! */

浙公网安备 33010602011771号