版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010590568/article/details/84848926
对一个没有开启多线程的基本的进程程序而言,只有一个进程,一个线程,就是主线程,所有的程序执行都是按照"过程"的方式,从头到尾,一步步执行。而多线程的引入就是希望能够一身多用,专注当前任务的同时能够分身去做别的事情,类似网络小说中的"分身"。
#include <stdio.h>
void print(char* msg)
{
for (int i = 0; i < 3; i++) {
printf("%s", msg);
fflush(stdout);
sleep(1);
}
}
int main(void)
{
void print(char*);
print("hello");
print("world!");
return 0;
}
这是一个很普通的单线程单进程的程序,输入的内容也是按照规定3个"hello",3个"world!"
接着看下面的程序
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* print_func(char* msg)
{
for (int i = 0; i < 3; i++) {
printf("%s", msg);
fflush(stdout);
sleep(1);
}
}
int main(void)
{
pthread_t pth1, pth2;
pthread_create(&pth1, NULL, print_func, (void*)"zhen");
pthread_create(&pth2, NULL, print_func, (void*)"shangxue!");
print_func("main pthread!");
print_func("main pthread!");
print_func("main pthread!");
pthread_join(pth1, NULL);
pthread_join(pth2, NULL);
return 0;
}
使用gcc code.c -std=c99 -pthread生成可执行文件 #多线程编译需要添加-pthread参数
从代码输出可以看出,主逻辑在执行自己任务的同时,子线程pht1和pth2分别根据传递的参数调用了自己对应的函数,而主线程在自己任务执行完以后再join的位置等待子线程的结束,回收资源!