ubuntu18.04 使用pthread库
作者:互联网
不需要安装包,但是编译的时候需要手动包含pthread包:g++ threadtest1.cpp -lpthread -o threadtest1
测试代码:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <unistd.h>
#define NUM_THREADS 20
//thread argument struct
typedef struct _thread_data {
int tid;
double studff;
} thread_data;
//thread function
void* thr_func(void* arg) {
thread_data* data = (thread_data*)arg;
printf("from thr_func, thread id:%d\n", data->tid);
pthread_exit(NULL);
return NULL;
}
int main() {
pthread_t thr[NUM_THREADS];
int i, rc;
//thread_data argument array
thread_data thr_data[NUM_THREADS];
//initialize and set thread datached
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
//create threads
for (i = 0; i < NUM_THREADS; ++i) {
thr_data[i].tid = i;
if ((rc = pthread_create(&thr[i], &attr, thr_func, &thr_data[i]))) {
fprintf(stderr, "error:pthread_create,rc: %d\n", rc);
return EXIT_FAILURE;
}
}
pthread_attr_destroy(&attr);
while (1) {}
return 0;
}
标签:include,attr,thread,pthread,thr,使用,ubuntu18.04,data 来源: https://www.cnblogs.com/maycpou/p/13935508.html