linux: 初识pthread

注意点

  • 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;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值