System::Threading::Mutex class
内容
[
隐藏
]Mutex class
Mutex implemnetation. Objects of this class should only be allocated using System::MakeObject() function. Never create instance of this type on stack or using operator new, as it will result in runtime errors and/or assertion faults. Always wrap this class into System::SmartPtr pointer and use this pointer to pass it to functions as argument.
class Mutex : public System::Threading::WaitHandle
方法
| 方法 | 描述 |
|---|---|
| Mutex() | RTTI 信息。 |
| Mutex(bool) | 构造函数。 |
| Mutex(bool, const String&) | 构造函数。 |
| ReleaseMutex() | 释放互斥体。 |
| static Remove(const String&) | 删除系统中的已命名互斥体。 |
| virtual Reset() | 重置互斥体状态。未实现。 |
| virtual Set() | 将互斥体设置为已发信号状态。未实现。 |
| WaitOne() override | 锁定互斥体。如有必要,执行无限等待。 |
| WaitOne(int) override | 锁定互斥体。如有必要,执行等待。 |
| WaitOne(TimeSpan) override | 锁定互斥体。如有必要,执行等待。 |
字段
| 字段 | 描述 |
|---|---|
| static WaitTimeout | 特殊值由函数返回;否则返回数组中已发信号对象的索引,如果超时且没有任何信号。 |
备注
#include "system/threading/mutex.h"
#include "system/threading/thread.h"
#include "system/console.h"
#include "system/convert.h"
#include "system/smart_ptr.h"
#include "system/string.h"
int main()
{
auto mutex = System::MakeObject<System::Threading::Mutex>();
System::String str;
const int THREADS_COUNT = 3;
std::vector<System::SharedPtr<System::Threading::Thread>> threads;
threads.reserve(THREADS_COUNT);
for (auto i = 0; i < THREADS_COUNT; ++i)
{
threads.push_back(System::MakeObject<System::Threading::Thread>([&mutex, &str]()
{
mutex->WaitOne();
str += u"Thread " + System::Convert::ToString(System::Threading::Thread::GetCurrentThreadId()) + u" started." + System::Environment::get_NewLine();
System::Threading::Thread::Sleep(200);
str += u"Thread " + System::Convert::ToString(System::Threading::Thread::GetCurrentThreadId()) + u" ended." + System::Environment::get_NewLine();
mutex->ReleaseMutex();
}));
threads[i]->Start();
}
System::Threading::Thread::Sleep(700);
System::Console::WriteLine(str);
return 0;
}
/*
This code example produces the following output:
Thread 1 started.
Thread 1 ended.
Thread 2 started.
Thread 2 ended.
Thread 3 started.
Thread 3 ended.
*/
另见
- Class WaitHandle
- Namespace System::Threading
- Library Aspose.Font for C++