【Linux】linux中线程的引出
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、线程编程实战:创建你的第一个多线程程序
1. 基础线程创建代码
2. 编译和运行
一、线程编程实战:创建你的第一个多线程程序
1. 基础线程创建代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>// 线程函数
void* thread_function(void* arg) {int thread_num = *(int*)arg;for (int i = 0; i < 5; i++) {printf("线程%d: 正在工作... %d\n", thread_num, i);sleep(1);}return NULL;
}int main() {pthread_t thread1, thread2;int num1 = 1, num2 = 2;printf("主线程开始(PID: %d)\n", getpid());// 创建线程1if (pthread_create(&thread1, NULL, thread_function, &num1) != 0) {perror("线程1创建失败");exit(1);}// 创建线程2if (pthread_create(&thread2, NULL, thread_function, &num2) != 0) {perror("线程2创建失败");exit(1);}// 等待线程结束pthread_join(thread1, NULL);pthread_join(thread2, NULL);printf("所有线程执行完毕!\n");return 0;
}
2. 编译和运行
# 编译(需要链接pthread库)
gcc -o thread_demo thread_demo.c -lpthread# 运行
./thread_demo