进程:基于进程的多任务处理是程序的并发执行。
线程:基于线程的多任务处理是同一程序的片段的并发执行。
C++ 多线程写法,从入门开始,一点点往下写,我也不知道能学到精通还是到放弃。
根据主流的一些博客技术文档,循序渐进,适于新手入门。
首先第一个程序是直接使用多线程创建函数创建多个线程。
编译的时候需要静态链接库文件pthread ,使用命令 g++ -o target target.cpp -lpthread 其中-lpthread 编译选项到位置可任意,
#include <pthread.h>
#include <iostream>
using namespace std;
#define NUM_THREADS 5
void* say_hello(void* args)//必须使用指针,因为线程创建函数这样要求的。
{
cout << "Hello thread !" << endl;
}
int main()
{
// 定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
if (ret != 0)
{