源文件
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
void* say_hello(void* args)
{
int* x = (int *)&args;
cout << "\nHello w3cschool!" << "ID: " << *x << endl;
}
int main()
{
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{
int ret = pthread_create(&tids[i], NULL, say_hello, (void *)i);
if (ret != 0)
{
cout << "pthread_create error: error_code=" << ret << endl;
}
}
pthread_exit(NULL);
}
编译
g++ pthread_main.cpp -lpthread -o pthread_main
fengxuewei@fengxuewei-Legion-Y7000-2019-PG0:~/UAV/C++_Folder/learn$ ./pthread_main
Hello w3cschool!ID: 0
Hello w3cschool!ID: 3
Hello w3cschool!ID: 2
Hello w3cschool!ID: 1
Hello w3cschool!ID: 4