C/C++ pthread

  1. std::mutex
#include <iostream>
#include <chrono>
#include <mutex>
#include <thread>

struct CriticalData{
  std::mutex mut;
};

void deadLock(CriticalData& a, CriticalData& b){

  std::unique_lock<std::mutex>guard1(a.mut,std::defer_lock);
  std::cout << "Thread: " << std::this_thread::get_id() << " first mutex" <<  std::endl;

  std::this_thread::sleep_for(std::chrono::milliseconds(1));

  std::unique_lock<std::mutex>guard2(b.mut,std::defer_lock);
  std::cout << "    Thread: " << std::this_thread::get_id() << " second mutex" <<  std::endl;

  std::cout << "        Thread: " << std::this_thread::get_id() << " get both mutex" << std::endl;
  std::lock(guard1,guard2);
  // do something with a and b
}

int main(){

  std::cout << std::endl;

  CriticalData c1;
  CriticalData c2;

  std::thread t1([&]{deadLock(c1,c2);});
  std::thread t2([&]{deadLock(c2,c1);});

  t1.join();
  t2.join();

  std::cout << std::endl;

}
  1. pthread_key_t
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_key_t   key;
void echomsg(int t)
{
        printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t);
}
void * child1(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(2);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
        printf("child1");
}
void * child2(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        //sleep(1);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
        printf("child2");

}
int main(void)
{
        int tid1,tid2;
        pthread_key_create(&key,(void (*)(void*))echomsg);
        pthread_create((pthread_t *)&tid1,NULL,child1,NULL);
        pthread_create((pthread_t *)&tid2,NULL,child2,NULL);
        sleep(10);
        pthread_key_delete(key);
        printf("main thread exit\n");
        return 0;
}


#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
 
pthread_key_t   key;
 
struct info
{
        int i;
        char buf[512];
};
void echomsg(info* t)
{
        printf("destructor excuted in thread %d,param=%d\n",pthread_self(),t->i);
        delete t;//前面传入的是内存的地址。所以可以delete
}
void * child1(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        struct info *in=new info();
        in->i=tid;
        pthread_setspecific(key,(void *)in);//这里传入的是in的内容,也就是new出来的内存的地址
        sleep(2);
        struct info *in2=(struct info*)pthread_getspecific(key);
        printf("thread %d returns %d\n",tid,in2->i);
        sleep(5);
}
/*
void * child2(void *arg)
{
        int tid=pthread_self();
        printf("thread %d enter\n",tid);
        pthread_setspecific(key,(void *)tid);
        sleep(1);
        printf("thread %d returns %d\n",tid,pthread_getspecific(key));
        sleep(5);
}
*/
int main(void)
{
        int tid1,tid2;
        printf("hello\n");
        pthread_key_create(&key,(void (*)(void*))echomsg);
        pthread_create((pthread_t *)&tid1,NULL,child1,NULL);
//      pthread_create((pthread_t *)&tid2,NULL,child2,NULL);
        sleep(10);
        pthread_key_delete(key);
        printf("main thread exit\n");
        return 0;
}

(void*)传入的就是32位一块内存区域。
1.传入void*(int)就是把int值放入这块内存,取出来的时候千万不要用"*"号
2.传入(void * )( & int)就是把int指针放入内存,你get出来的时候就要记得用“ * ”号了

  1. pthread_mutex_timedlock
#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<cstdlib>
int main(void){
    int err;
    struct timespec tout;
    struct tm *tmp;
    char buf[64];

    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_lock(&lock);
    printf("mutex is locked!\n");

    clock_gettime(CLOCK_REALTIME,&tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf,sizeof(buf),"%r",tmp);
    printf("current time is %s\n",buf);
    tout.tv_sec += 10;

    err = pthread_mutex_timedlock(&lock,&tout);
    clock_gettime(CLOCK_REALTIME,&tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf,sizeof(buf),"%r",tmp);
    printf("the time is now %s\n",buf);
    if (err == 0)
        printf("mutex locked again!\n");
    else
        printf("can’t lock mutex again: %s\n", strerror(err));
    exit(0);

}

mutex is locked!
current time is 12:04:52 PM
the time is now 12:05:02 PM
can’t lock mutex again: Connection timed out

  1. 主线程写,子线程读
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
 
#define MAXSIZE 1024
 
void *func(void *arg);
char buff[MAXSIZE];
pthread_mutex_t mutex;
 
int main()
{
    void* exit_value;
    
    pthread_t tid;
    //create thread
    if(pthread_create(&tid,NULL,func,NULL)!=0){
        perror("pthread_create");
        exit(EXIT_FAILURE);
    }
 
    //init mutex
    if(pthread_mutex_init(&mutex,NULL)!=0){
        perror("pthread_mutex_init");
        exit(EXIT_FAILURE);
    }
 
    
    while(1)
    {
        pthread_mutex_lock(&mutex); //lock
        printf("Enter(end to quit):");
        fflush(stdout);
        scanf("%s",buff);
        if(strncmp(buff,"end",3)==0){
            pthread_mutex_unlock(&mutex);  //unlock
            break;
        }
        pthread_mutex_unlock(&mutex);  //unlock
        sleep(1);
    }
 
 
    //等待进程结束
    printf("join......\n");
    if(pthread_join(tid,&exit_value)!=0){
        perror("pthread_join");
        exit(EXIT_FAILURE);
    }
    
    //destory mutex
    pthread_mutex_destroy(&mutex);
    exit(0);
}
 
void *func(void *arg)
{
    sleep(1);
    
    while(1)
    {
        pthread_mutex_lock(&mutex);//lock
        if(strlen(buff)!=0){
            if(strncmp(buff,"end",3)==0){
                pthread_mutex_unlock(&mutex);//unlock
                pthread_exit(0);
            }
           printf("read %d bytes\n",strlen(buff));
           buff[0]='\0';
           pthread_mutex_unlock(&mutex);  //unlock
           sleep(1);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值