simple code for c++ condition_variable and mutex

#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>


#include <iostream>
#include <condition_variable>
#include <chrono>
#include <mutex>

std::mutex data_mutex_;
std::condition_variable data_notifier_;

int  condition_variable_flag = -1;

std::uint64_t get_ms_time()
{
    std::uint64_t sec_cnt = 0, usec_cnt =0;
    struct timeval tv;
    std::uint64_t ms_sec_cnt;

    gettimeofday(&tv, NULL);
    sec_cnt  = tv.tv_sec;
    usec_cnt = tv.tv_usec;
    ms_sec_cnt  = sec_cnt*1000;
    ms_sec_cnt  = ms_sec_cnt+ usec_cnt/1000;

    return ms_sec_cnt;
}



void *thread1(void *args)
{
	printf("enter thread1 %lu\n", get_ms_time());
    std::unique_lock<std::mutex> lock(data_mutex_);
    condition_variable_flag = 0;
    while(condition_variable_flag == 0)
    {
        printf("thread1:readd in condition queue %lu\n", get_ms_time());
        data_notifier_.wait_for(lock, std::chrono::milliseconds(200));
    }
    printf("thread1:exit condition satisfy %lu\n", get_ms_time());
    condition_variable_flag = false;
}

void *thread2(void *args)
{
    while(condition_variable_flag<0)
    {
        usleep(1000);
    }
    printf("enter thread2  %lu\n", get_ms_time());
    {
        std::unique_lock<std::mutex> lock(data_mutex_);
        condition_variable_flag = 1;
        data_notifier_.notify_all();
    }
}


int main(int argc, char const *argv[])
{
	condition_variable_flag = -1;

    {
        pthread_t      thread_t;
        pthread_attr_t attr;
        size_t         stacksz;
        #define S_PTHREAD_STACK_MIN (512*1024)

        pthread_attr_init (&attr);
        stacksz = S_PTHREAD_STACK_MIN*100;
        if(pthread_attr_setstacksize(&attr, stacksz))
        {
            printf("set pthread stack sz to %u fail!!\n",(unsigned int)stacksz);
    	}

        pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
        pthread_create (&thread_t, &attr, thread1, (void *)NULL);
    }

    {
        pthread_t      thread_t;
        pthread_attr_t attr;
        size_t         stacksz;
        #define S_PTHREAD_STACK_MIN (512*1024)

        pthread_attr_init (&attr);
        stacksz = S_PTHREAD_STACK_MIN*100;
        if(pthread_attr_setstacksize(&attr, stacksz))
        {
            printf("set pthread stack sz to %u fail!!\n",(unsigned int)stacksz);
        }

        pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
        pthread_create (&thread_t, &attr, thread2, (void *)NULL);
    }

    while(1)
    {
    	sleep(1);
    }
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值