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

标签 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();
下面是我的 UML。它肯定有一些缺点
enter image description here

最佳答案

It definitely has some faults


是的,例如:
  • 都在hello执行前join完成,这是不可能的
  • 每个连接都在一个分离的线程中执行,这必须由主
  • 完成。
  • 有叉但没有连接(UML 的)
  • Action 解锁后,流程转到 t2.join,这是 false 并产生一个永无止境的循环

  • 在序列图中,可以使用组合片段关键,但事件中没有特定符号来指示关键区域。
    第一种可能性是不尝试指示临界区,使用互斥锁上的调用操作 Action 来调用锁定和解锁,读者必须知道这意味着什么。您还可以添加注释以帮助读者。例如(对 hello 的调用被它的主体替换,我用一个不透明的 Action 替换了循环以简化):
    enter image description here
    或与分区:
    enter image description here
    第二种方法是使用组合片段关键,即使这在规范中没有指定,希望读者理解(可能在注释的帮助下):
    enter image description here
    当然,您可以使用第一种方式进行组合,也可以绘制组合片段关键希望对读者有所帮助:
    enter image description here
    如果你不想有对应于 C++ 的 Action ,第三种方法是使用接受/发送信号 Action 模拟临界区,但坦率地说,这并不容易阅读/理解:
    enter image description here
    或与分区:
    enter image description here
    当然也可以在 fork 之后做第一个发送信号 Action :
    enter image description here

    关于c++ - 如何绘制 UML 来说明在临界区工作的 2 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64195050/

    相关文章:

    C++模板函数指针

    Python 多线程 - 使用 While 语句运行时未释放内存

    android - 如何在按钮单击事件中调用异步任务

    c++ - 比较两个字符串数组c++

    c++ - Visual Studio 6 何时捕获结构化异常?

    ios - 在后台线程写入 Realm 后,主线程看不到更新的数据

    asp.net - "Unified Modelling Language"的简单解释,为什么它很重要?

    c++ - UML 对描述模板化代码有用吗?

    uml - 聚合与组合

    c++ - 在C++中,虽然它具有指针作为属性,但是有一种保存对象然后重新加载的方法吗?