c++11 多线程传参和生产者消费者实现
生活随笔
收集整理的这篇文章主要介绍了
c++11 多线程传参和生产者消费者实现
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
普通函数传参和成员函数传参
#include <iostream> #include <thread> #include <windows.h> void func(int x) {for (int i = 1; i <= 10; i++) {printf("%d\n", x);Sleep(100);} }class A{ public:void func(int x) {for (int i = 1; i <= 10; i++) {printf("%d\n", 2);Sleep(100);}} }; int main() {A a;std::thread(&A::func, &a, 2).detach(); // 成员函数多线程这样写std::thread(func, 1).detach();getchar(); // 如果主进程结束那么子线程也会死return 0; }生产者消费者
#include <iostream> #include <thread> #include <mutex> #include <vector> #include <windows.h>std::vector<int> data; // 临界区 std::mutex mux; // 全局互斥锁/** “生产者-消费者”问题的实现,我的理解是:通过竞争互斥锁来间接实现对临界区的互斥访问。 同一时间段内,只有一个线程得到了 mux 互斥锁,那么接下来对临界区的操作自然也是互斥的,直到释放这个互斥锁。 **/ void product_thread(){while(true){std::unique_lock<std::mutex> lock(mux);if (data.size() >= 5) {lock.unlock();continue;}data.push_back(1);printf("----生产\n");lock.unlock();Sleep(200);} }void consume_thread(){while (true){std::unique_lock<std::mutex> lock(mux);if(data.empty()) {lock.unlock();continue;}printf("消耗\n");data.pop_back();lock.unlock();Sleep(1000);} }int main() {std::thread thread_product(&product_thread);std::thread thread (&consume_thread);thread_product.join();thread.join();return 0; }总结
以上是生活随笔为你收集整理的c++11 多线程传参和生产者消费者实现的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: wxWidgets 编译 ICON 资源
- 下一篇: 静态链接库编写与使用(VC6)