我有一个小程序,它在同一个临界区运行 2 个线程并使用互斥锁。该程序运行良好。但我想画一个 UML,最好是事件或状态图,说明 2 个线程运行相同的临界区,而不是代码的不同部分。请帮我修改我的 UML。
下面是源代码:
#include <iostream>
#include <thread>
#include <mutex>
#include <stdio.h>
/* Global variables where both threads have access to*/
std::mutex myMutex;
int globalVariable = 1;
/* CRITICAL SECTION */
void hello()
{
myMutex.lock();
for (int counter =0 ; counter< 100; counter++){
//std::lock_guard<std::mutex> lock(myMutex);
printf("%d ",std::this_thread::get_id() ); //print the id of the thread that executes the for loop
globalVariable++;
}
printf("Thread with id = %d runs. Counter is %d \n", std::this_thread::get_id(), msg) ; //print the result counter value and thread id that finishes the for loop
myMutex.unlock();
}
int main()
{
std::thread t1(hello);
std::thread t2(hello);
t1.join();
t2.join();
下面是我的 UML。它肯定有一些缺点最佳答案
It definitely has some faults
是的,例如:
在序列图中,可以使用组合片段关键,但事件中没有特定符号来指示关键区域。
第一种可能性是不尝试指示临界区,使用互斥锁上的调用操作 Action 来调用锁定和解锁,读者必须知道这意味着什么。您还可以添加注释以帮助读者。例如(对 hello 的调用被它的主体替换,我用一个不透明的 Action 替换了循环以简化):
或与分区:
第二种方法是使用组合片段关键,即使这在规范中没有指定,希望读者理解(可能在注释的帮助下):
当然,您可以使用第一种方式进行组合,也可以绘制组合片段关键希望对读者有所帮助:
如果你不想有对应于 C++ 的 Action ,第三种方法是使用接受/发送信号 Action 模拟临界区,但坦率地说,这并不容易阅读/理解:
或与分区:
当然也可以在 fork 之后做第一个发送信号 Action :
关于c++ - 如何绘制 UML 来说明在临界区工作的 2 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64195050/