C++11,thread,sleep,锁

本文详细介绍了C++中使用std::this_thread::sleep_for进行线程睡眠的方法,包括秒、毫秒和微秒级别的精确控制。通过示例代码展示了如何测量线程睡眠的实际时间,并提供了多个参考资料,帮助读者深入理解线程管理和计时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相关链接:https://blog.csdn.net/knowledgebao/article/details/85076661


sleep:

#include <thread>
#include <iostream>
auto start = std::chrono::high_resolution_clock::now();

std::this_thread::sleep_for(std::chrono::seconds(1));//1秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));//1毫秒
std::this_thread::sleep_for(std::chrono::microseconds(1));//1微秒

auto end = std::chrono::high_resolution_clock::now();

std::chrono::duration<double, std::milli> elapsed = end - start;
std::cout << "Waited " << elapsed.count() << " ms\n";

 

 

参考资料:

1,https://my.oschina.net/yepanl/blog/2055078

2,https://docs.microsoft.com/zh-cn/previous-versions/hh920528(v=vs.120)

3,https://blog.csdn.net/Sandy_WYM_/article/details/83538635

4,http://www.runoob.com/w3cnote/cpp-std-thread.html

5,https://www.cnblogs.com/diegodu/p/7099300.html


如果有任何问题,请联系:knowledgebao@163.com

C11标准库中提供了读写,可以用来实现多个线程对同一资源的并发读写操作。下面是使用读写的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <threads.h> int data = 0; rwlock_t lock; int reader(void* arg) { int id = *(int*)arg; while (1) { thrd_sleep((struct timespec){.tv_sec = 1}, NULL); // 模拟读操作 // 加读 rwlock_rdlock(&lock); printf("Reader %d read data: %d\n", id, data); // 释放读 rwlock_unlock(&lock); } return 0; } int writer(void* arg) { int id = *(int*)arg; while (1) { thrd_sleep((struct timespec){.tv_sec = 2}, NULL); // 模拟写操作 // 加写 rwlock_wrlock(&lock); data++; printf("Writer %d write data: %d\n", id, data); // 释放写 rwlock_unlock(&lock); } return 0; } int main(int argc, char const *argv[]) { // 初始化读写 rwlock_init(&lock); // 创建3个读线程 thrd_t readers[3]; int readerIds[3]; for (int i = 0; i < 3; i++) { readerIds[i] = i + 1; thrd_create(&readers[i], reader, &readerIds[i]); } // 创建2个写线程 thrd_t writers[2]; int writerIds[2]; for (int i = 0; i < 2; i++) { writerIds[i] = i + 1; thrd_create(&writers[i], writer, &writerIds[i]); } // 等待所有线程结束 for (int i = 0; i < 3; i++) { thrd_join(readers[i], NULL); } for (int i = 0; i < 2; i++) { thrd_join(writers[i], NULL); } // 销毁读写 rwlock_destroy(&lock); return 0; } ``` 这个示例程序中有3个读线程和2个写线程,读线程每隔1秒钟读一次共享变量data的值,写线程每隔2秒钟写一次共享变量data的值。读线程和写线程之间会相互竞争读写,以实现对共享变量的并发访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值