注意点
- pthread_create 与pthread_join成对出现
- 注意传参格式,pthread_create(&线程id, NULL, (func *)类型函数地址, (void *)变量或结构体地址);,函数定义则是void *函数名(void *arg),函数内部要先把void指针arg强转为指定类型,如结构体可以新声明一个变量。
也可以写成printf("My name is %s, age is %d\n", ((struct Mystruct *)arg)->name, ((struct Mystruct *)arg)->age);
- 引入<pthread.h>, 编译引入静态链接库-lpthread
单次读入,与pthread_join配对
#include<stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
//void *print(void *arg);
struct Mystruct{
char name[20];
int age;
};
void *print(void *arg){
struct Mystruct m = *(struct Mystruct *)arg;
printf("My name is %s, age is %d\n", m.name, m.age);
//sleep(2);
printf("thread goes to the end\n");
}
int main(){
pthread_t tid;
struct Mystruct mystruct;
strcpy(mystruct.name, "fang");
mystruct.age = 18;
printf("Thread is working...\n");
pthread_create(&tid, NULL, print, (void *)&mystruct);
pthread_join(tid, NULL);
sleep(30);
return 0;
}
循环读入,在函数中加入pthread_exit
#include<stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
struct Mystruct{
char name[20];
int age;
};
void *print(void *arg){
//struct Mystruct m = *(struct Mystruct *)arg;
printf("My name is %s, age is %d\n", ((struct Mystruct *)arg)->name, ((struct Mystruct *)arg)->age);
//sleep(2);
printf("thread goes to the end\n");
pthread_exit(NULL);
printf("KILLITSELF\n");//无法输出
}
int main(){
pthread_t tid;
struct Mystruct mystruct;
//mystruct.name = "fang";
strcpy(mystruct.name, "fang");
mystruct.age = 18;
while(1){
scanf("%d", &mystruct.age);
printf("Thread is working...\n");
pthread_create(&tid, NULL, print, (void *)&mystruct);
//pthread_join(tid, NULL);
//pthread_cancel(tid);//需要延时
}
sleep(30);
return 0;
}
pthread_detach线程分离??后面不能用join
多线程实现累加到10000
- 注意加锁操作,并及时解锁,防止死锁!
后来在编译无参数print时遇到了很狗血的问题,NULL转为(void *)NULL就不认,此处注意一定要用gcc而不是g++, 摘自一博客:
#include<stdio.h>
#include <pthread.h>
#include <unistd.h>
int now;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *print(){
while(1){
pthread_mutex_lock(&mutex);
if (now >= 10000){
pthread_mutex_unlock(&mutex);
break;
}
now++;
printf("%d\n", now);
pthread_mutex_unlock(&mutex);
}
}
int main(){
pthread_t tid[2];
//并发
pthread_create(&tid[0], NULL, print, (void *)NULL);
pthread_create(&tid[1], NULL, print, (void *)NULL);
for (int i = 0; i < 2; i++){
pthread_join(tid[i], NULL);
}
return 0;
}