托管C++线程锁实现 c++11线程池
托管C++线程锁实现
最近由于工作需要,开始写托管C++,由于C++11中的mutex,和future等类,托管C++不让调用(报错),所以自己实现了托管C++的线程锁。
该类可确保当一个线程位于代码的临界区时,另一个线程不会进入该临界区。 如果其他线程尝试进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。
1 using namespace System;
2 using namespace System::Threading;
3
4 ref class Lock
5 {
6 public:
7 Lock(Object ^ pObject)
8 : m_pObject(pObject)
9 {
10 Monitor::Enter(m_pObject);
11 }
12
13 ~Lock()
14 {
15 Monitor::Exit(m_pObject);
16 }
17
18 private:
19 Object ^ m_pObject;
20 };
注:原则上m_pObject是可以为任意类型,但是String是一个例外。
String也是应用类型,从语法上来说是没有错的。
但是锁定字符串尤其危险,因为字符串被公共语言运行库 (CLR)“暂留”。 这意味着整个程序中任何给定字符串都只有一个实例,就是这同一个对象表示了所有运行的应用程序域的所有线程中的该文本。因此,只要在应用程序进程中的任何位置处具有相同内容的字符串上放置了锁,就将锁定应用程序中该字符串的所有实例。通常,最好避免锁定 public 类型或锁定不受应用程序控制的对象实例。例如,如果该实例可以被公开访问,则 lock(this) 可能会有问题,因为不受控制的代码也可能会锁定该对象。这可能导致死锁,即两个或更多个线程等待释放同一对象。出于同样的原因,锁定公共数据类型(相比于对象)也可能导致问题。而且lock(this)只对当前对象有效,如果多个对象之间就达不到同步的效果。lock(typeof(Class))与锁定字符串一样,范围太广了。
c++11线程池
1 #pragma once
2
3 #include <future>
4
5 #include <vector>
6
7 #include <atomic>
8
9 #include <queue>
10
11 #include <thread>
12
13 #include <mutex>
14
15 namespace std {
16
17 //线程池最大容量,应尽量设小一点
18 #define THREADPOOL_MAX_NUM 16
19
20 class ThreadPool
21 {
22 public:
23 ThreadPool(unsigned short size = 1) { AddThread(size); }
24 ~ThreadPool()
25 {
26 if (_run.load())
27 {
28 Close();
29 }
30 }
31
32 void Close()
33 {
34 _run.store(false);
35 //唤醒所有线程执行
36 _task_cv.notify_all();
37 for (thread &th : _pool)
38 {
39 if (th.joinable())
40 th.join();
41 }
42 }
43
44 //提交一个任务,
45 template<class F, class... Args>
46 auto commit(F&& f, Args&&... args) ->future<decltype(f(args...))>
47 {
48 if (!_run)
49 throw runtime_error("commit on ThreadPool is stop.");
50 // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
51 using RetType = decltype(f(args...));
52 //把函数入口及参数打包
53 auto task = make_shared<packaged_task<RetType()>>(bind(forward<F>(f), forward<Args>(args)...));
54
55 future<RetType> future = task->get_future();
56 {
57 lock_guard<mutex> lock{ _lock };
58 _tasks.emplace([task]() {(*task)(); });
59 }
60 #ifdef THREADPOOL_AUTO_GROW if (_id1ThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM) AddThread(1); #endif _task_cv.notify_one(); return future; }
61
62 int IdlCount() { return _id1ThrNum; }
63 int BusyCount() { return _pool.size(); }
64
65 void AddThread(unsigned short size)
66 {
67 for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size)
68 {
69 _pool.emplace_back([this] {
70 while (_run.load())
71 {
72 Task task;
73 {
74 unique_lock<mutex> lock{ _lock };
75 _task_cv.wait(lock, [this]
76 {
77 return !_run.load() || !_tasks.empty();
78 });
79 if (!_run.load() && _tasks.empty())
80 return;
81 task = move(_tasks.front());
82 _tasks.pop();
83 }
84 _id1ThrNum--;
85 task();
86 _id1ThrNum++;
87 }
88 });
89 _id1ThrNum--;
90 }
91 }
92
93 public:
94 //定义类型
95 using Task = std::function<void()>;
96 //线程池
97 vector<thread> _pool;
98 //锁
99 mutex _lock;
100 //任务队列
101 queue<Task> _tasks;
102 //条件阻塞
103 condition_variable _task_cv;
104 //线程是否在执行
105 atomic<bool> _run{ true };
106 //空闲线程
107 atomic<int> _id1ThrNum{ 0 };
108 };
109 }



浙公网安备 33010602011771号