C language scrap 3: Use pure software to replace Mutex mutex-multithreading

I. Introduction

In the previous article, a pure software algorithm was introduced to realize the protection function of the critical section . Article link: C language scrap 2: Use pure software to replace the Mutex mutex .

First of all, make it clear: If the mutex provided by the operating system can achieve the functions I need, I will definitely use the mutex. The reason why the Peterson algorithm is introduced is mainly because it is more interesting and small , which can bring us some Some ideas outside of "normative" programming.

There are also some friends in the background who have posted some comments on this algorithm. As long as they have good ideas, they are afraid not to think about it.

One of my friends mentioned that this algorithm can only be used in 2 threads. Are there other similar algorithms that can be used in multiple threads ?

After get off work in the evening, I took a moment to find the algorithm below and share it!

Two, Micha Hofri algorithm

I didn't find a name for this algorithm. Let's call this algorithm by the author's name for the time being!

Algorithm screenshot:

From the main code of the algorithm, the Hofri algorithm mainly extends the Peterson algorithm, using two global variable arrays to control which thread can enter the critical section.

The argument for this algorithm is more complicated , and they are all mathematical proofs. The article is here: Proof of a Mutual Exclusion Algorithm-- A `Class'ic Example , published in 1989. Interested friends can burn their brains for research.

Three, test code

// 线程操作的资源
static int num = 0;

// 创建 10 个线程
#define THREAD_NUM      10

// 这 2 个全局变量控制算法
int flag[THREAD_NUM] = {0 };
int turn[THREAD_NUM - 1] = {0};

// 这是线程函数
void *thread_routine(void *arg)
{
    int index = *(int *)arg;

    for (int i = 0; i < 10000; ++i)
    {
        for (int j = 1; j < THREAD_NUM - 1; j++)
        {
            flag[index] = j;
            turn[j] = index;
    L:
            for (int k = 1; k < THREAD_NUM; ++k)
            {
                if (k == index) continue;
                if ((flag[k] >= j) && turn[j] == index)
                    goto L;
            }

        }

        flag[index] = THREAD_NUM;
        
        // 关键代码段
        num++;
        
        flag[index] = 0;
    }
    return NULL;
}

void test()
{
    // 用来传递线程的索引
    int index[THREAD_NUM] = {0};
    
    创建多个线程,执行同一个函数
    pthread_t t[THREAD_NUM];
    for (int i = 0; i < THREAD_NUM; ++i)
    {
        index[i] = i;
        pthread_create(&t[i], NULL, thread_routine, &index[i]);
    }
}

Compile and execute. After all threads are executed, the shared resource num variable can get the correct result.

Four, summary

Let me repeat what I said at the beginning of the article. The algorithm here only shows that it can complete the function of protecting the critical section. However, in actual projects, it is really not recommended to use it like this. After all, the maintainability of the code is very important!



Recommended reading

[C language]
1. C language pointer-from the underlying principle to fancy skills, with pictures and codes to help you explain thoroughly
2. The original gdb underlying debugging principle is so simple
3. Step by step analysis-how to use C to achieve object-oriented programming
4. A weapon to improve code compulsion: macro definition-from entry to abandonment
5. Use setjmp and longjmp in C language to implement exception capture and coroutine

[Application design]
1. They all say that the software architecture should be layered and divided into modules, and how to do it (1)
2. They all say that the software architecture needs to be layered and divided into modules, and how to do it (2)
3. IoT gateway Development: MQTT message bus-
based design process (Part 1) 4. IoT gateway development: MQTT message bus-based design process (Part 2)
5. My favorite method of communication between processes-message bus

[Operating System]
1. Why do spacecraft and missiles prefer to use microcontrollers instead of embedded systems?

[Internet of Things]
1. Those things about encryption and certificates
2. Deepen the LUA scripting language, let you fully understand the principle of debugging

[Nonsense] 1. Based
on my failed career experience: a few tips for technicians who are new to the workplace

Guess you like

Origin blog.csdn.net/u012296253/article/details/115366917