如何绘制 UML 来说明在临界区工作的 2 个线程

Min*_*ham 8 c++ multithreading uml mutex

我有一个小程序,它在同一个临界区运行 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();
Run Code Online (Sandbox Code Playgroud)

下面是我的 UML。它肯定有一些缺点 在此处输入图片说明

bru*_*uno 6

它肯定有一些缺点

是的,例如:

  • 双方携手完成之前执行你好,这是不可能的
  • 每个连接都在一个单独的线程中执行,这必须由main完成
  • 有一个叉子但没有连接(UML 一个)
  • 动作解锁后,流程进入t2.join这是假的,并产生一个永无止境的循环

在序列图中,可以使用组合片段 critical,但活动中没有特定符号来指示关键区域。

第一种可能性是不尝试指示临界区,使用互斥锁上的调用操作操作来调用lockunlock,读者必须知道这意味着什么。您还可以添加注释以帮助读者。例如(对hello的调用被它的主体替换,我用一个不透明的动作替换了循环以简化):

在此处输入图片说明

或与分区:

在此处输入图片说明

第二种方法是使用组合片段关键,即使这在规范中没有指定,希望读者理解(可能在注释的帮助下):

在此处输入图片说明

当然,您可以使用第一种方式进行组合,也可以绘制组合片段关键希望对读者有所帮助:

在此处输入图片说明

如果你不想有对应于 C++ 的动作,第三种方法是使用接受/发送信号动作模拟临界区,但坦率地说,这并不容易阅读/理解:

在此处输入图片说明

或与分区:

在此处输入图片说明

当然也可以在fork之后做第一个发送信号动作:

在此处输入图片说明