Home Database Mysql Tutorial [RTT例程练习] 2.6 互斥锁 mutex

[RTT例程练习] 2.6 互斥锁 mutex

Jun 07, 2016 pm 03:17 PM
mutex mutually exclusive practise

互斥锁是一种保护共享资源的方法。当一个线程拥有互斥锁的时候,另一个线程若是等待锁,则其就会被挂起,从而保证只有一个线程会操作共享数据。 这里的例子同样有静态锁和动态锁,其差别同之前一样,仅仅是创建和删除的方式不同。 例子中,线程2 一开始拥有

互斥锁是一种保护共享资源的方法。当一个线程拥有互斥锁的时候,另一个线程若是等待锁,则其就会被挂起,从而保证只有一个线程会操作共享数据。

这里的例子同样有静态锁和动态锁,其差别同之前一样,仅仅是创建和删除的方式不同。

例子中,线程2 一开始拥有锁,因为线程2的优先级高。而后线程1一开始采用等待10个tick的方式,所以线程1等锁的时候一定会超时。最后线程2 等1秒之后释放锁,然后这时线程1再次试图拥有锁,就能成功拿到锁了。

代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

#include <rtthread.h>

 

void rt_init_thread_entry(void *parameter)

{

 

}

 

static struct rt_mutex static_mutex;

 

static rt_mutex_t dynamic_mutex = RT_NULL;

 

static rt_uint8_t thread1_stack[1024];

struct rt_thread thread1;

static void rt_thread_entry1(void *parameter)

{

    rt_err_t result;

    rt_tick_t tick;

     

    /* static mutex demo */

    rt_kprintf("thread1 try to get static mutex, wait 10 ticks.\n");

     

    tick = rt_tick_get();

     

    result = rt_mutex_take(&static_mutex, 10);

    if (result == -RT_ETIMEOUT)

    {

        if (rt_tick_get() - tick != 10)

        {

            rt_mutex_detach(&static_mutex);

            return ;

        }

    }

    else

    {

        rt_kprintf("thread1 take a static mutex, failed.\n");

        rt_mutex_detach(&static_mutex);

        return ;

    }

     

    /* wait forever */

    rt_kprintf("thread1 try to get static mutex, wait forever.\n");

    result = rt_mutex_take(&static_mutex, RT_WAITING_FOREVER);

    if (result != RT_EOK)

    {

        rt_kprintf("thread1 take a static mutex, failed.\n");

        rt_mutex_detach(&static_mutex);

        return ;

    }

     

    rt_kprintf("thread1 take a static mutex, done.\n");

     

    rt_mutex_detach(&static_mutex);

     

    /* dynamic mutex test */

    rt_kprintf("thread1 try to get dynamic mutex, wait 10 ticks.\n");

     

    tick = rt_tick_get();

     

    result = rt_mutex_take(dynamic_mutex, 10);

    if (result == -RT_ETIMEOUT)

    {

        if (rt_tick_get() - tick != 10)

        {

            rt_mutex_delete(dynamic_mutex);

            return ;

        }

        rt_kprintf("thread1 take dynamic mutex timeout.\n");

    }

    else

    {

        rt_kprintf("thread1 take a dynamic mutex, failed.\n");

        rt_mutex_delete(dynamic_mutex);

        return ;

    }

     

    rt_kprintf("thread1 try to take dynamic mutex, wait forever.\n");

    result = rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);

    if (result != RT_EOK)

    {

        rt_kprintf("thread1 take a dynamic mutex, failed.\n");

        rt_mutex_delete(dynamic_mutex);

        return ;

    }

     

    rt_kprintf("thread1 take a dynamic mutex,done.\n");

    rt_mutex_delete(dynamic_mutex);

}

 

static rt_uint8_t thread2_stack[1024];

struct rt_thread thread2;

static void rt_thread_entry2(void *parameter)\

{

    //rt_err_t result;

    //rt_tick_t tick;

     

    rt_kprintf("thread2 try to take static mutex.\n");

    rt_mutex_take(&static_mutex, 10);

    rt_kprintf("thread2 got static mutex.\n");

    rt_thread_delay(RT_TICK_PER_SECOND);

    rt_kprintf("thread2 release static mutex.\n");

    rt_mutex_release(&static_mutex);

     

    rt_kprintf("thread2 try to take dynamic mutex.\n");

    rt_mutex_take(dynamic_mutex, 10);

    rt_kprintf("thread2 got dynamic mutex.\n");

    rt_thread_delay(RT_TICK_PER_SECOND);

    rt_kprintf("thread2 release dynamic mutex.\n");

    rt_mutex_release(dynamic_mutex);

}

 

int rt_application_init()

{

    //rt_thread_t init_thread;

    rt_err_t result;

     

    result = rt_mutex_init(&static_mutex, "smutex", RT_IPC_FLAG_FIFO);

    if (result != RT_EOK)

    {

        rt_kprintf("init static mutex failed.\n");

        return -1;

    }

    dynamic_mutex = rt_mutex_create("dmutex", RT_IPC_FLAG_FIFO);

    if (dynamic_mutex == RT_NULL)

    {

        rt_kprintf("create dynamic mutex failed.\n");

        return -1;

    }

 

    rt_thread_init(&thread1,

                   "thread1",

                   rt_thread_entry1,

                   RT_NULL,

                   &thread1_stack[0],

                   sizeof(thread1_stack),11,5);

    rt_thread_startup(&thread1);

 

 

    rt_thread_init(&thread2,

                   "thread2",

                   rt_thread_entry2,

                   RT_NULL,

                   &thread2_stack[0],

                   sizeof(thread2_stack),10,5);

    rt_thread_startup(&thread2);

    return 0;

}</rtthread.h>

Copy after login

结果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

thread2 try to get static mutex

thread2 got static mutex

thread1 try to get static mutex, wait 10 ticks.

thread1 take static mutex timeout

thread1 try to get static mutex, wait forever.

thread2 release static mutex

thread2 try to get dynamic mutex

thread2 got dynamic mutex

thread1 take a staic mutex, done.

thread1 try to get dynamic mutex, wait 10 ticks.

thread1 take dynamic mutex timeout

thread1 try to get dynamic mutex, wait forever.

thread2 release dynamic mutex

thread1 take a dynamic mutex, done.

Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to practice typing with Kingsoft Typing Guide - How to practice typing with Kingsoft Typing Guide How to practice typing with Kingsoft Typing Guide - How to practice typing with Kingsoft Typing Guide Mar 18, 2024 pm 04:25 PM

Nowadays, many friends like to use Kingsoft Typing Assistant, but the typing speed seriously affects work efficiency, so I teach you to practice typing speed. So how to use Kingsoft Typing Assistant to practice typing? Today, the editor will give you a tutorial on how to practice typing numbers with Kingsoft Typing Assistant. The following is described, I hope it will be helpful to everyone. First, open the Kingsoft typing software, then click the (Getting Started) button with your mouse, then click the (Number Keys) button in a new window, then click the (Start from Scratch) button below to practice, or click the (Test Mode) button. , just enter numbers for practice. In addition, Kingsoft Typing Assistant has other functions that can help you practice typing better. 1. Select practice mode: On the software interface, you can see that there are different practice modes, such as &quot;New

How to practice Wubi typing for beginners - Wubi input method typing practice How to practice Wubi typing for beginners - Wubi input method typing practice Mar 18, 2024 pm 06:30 PM

Wubi typing, also known as Wubi input method, is an efficient Chinese character input method. For beginners, mastering Wubi typing requires a certain amount of time and patience. Below, the editor has compiled the learning methods for Wubi typing beginners. Let’s take a look! 1. Understand the principles of Wubi font Wubi font is a type of font based on Input method for strokes and radicals. Each Chinese character can be composed of different strokes and radicals. Therefore, the key to learning Wubi font is to understand the combination rules of strokes and root characters. In the five-stroke font, there are five basic strokes: horizontal, vertical, left, right, and fold. These basic strokes can be combined into different radicals, which in turn can be combined into complete Chinese characters. 2. Learn the radicals and key positions. In Wubi font, each letter key corresponds to one or more radicals. therefore

Golang compilation error: 'undefined: sync.Mutex' How to solve it? Golang compilation error: 'undefined: sync.Mutex' How to solve it? Jun 24, 2023 pm 06:12 PM

Compilation errors are a very common problem during development using golang. When you encounter the error: "undefined: sync.Mutex", it means that you are trying to use a type called sync.Mutex, which is not imported and declared correctly. So how to solve this problem? First, we need to understand what sync.Mutex is. sync.Mutex is a lock type in the golang standard library, which is used to implement mutually exclusive access to critical sections. in g

Implementation of mutual exclusion and critical section of C++ functions in concurrent programming? Implementation of mutual exclusion and critical section of C++ functions in concurrent programming? Apr 28, 2024 am 08:42 AM

In concurrent programming, mutexes and critical sections are used to prevent data races. Mutex is a data structure that allows only one thread to access shared resources at a time. The specific implementation is as follows: Define a Mutex class with atomic tags. Use the test_and_set() method to lock and the clear() method to unlock. The critical section is a section of code that can only be executed by one thread at a time. The specific implementation is as follows: declare a mutex. Use the lock_guard wrapper to access shared resources in critical sections.

Regular expression exercises in Java Regular expression exercises in Java Jun 16, 2023 pm 02:36 PM

In Java, regular expressions are one of the most commonly used technologies and can be used in almost any text processing scenario, such as text search, extraction, analysis, replacement, etc. Its powerful matching capabilities can greatly improve development efficiency, while making the code more concise and easier to maintain. The following are some regular expression exercises in Java to help you master the application of regular expressions. Regular expression for matching Chinese characters: [u4e00-u9fa5] Explanation: The Unicode code value range of Chinese characters is from 4e00 to 9f

How to handle multi-thread synchronization and mutually exclusive access in C# development How to handle multi-thread synchronization and mutually exclusive access in C# development Oct 08, 2023 pm 05:57 PM

How to handle multi-thread synchronization and mutually exclusive access in C# development requires specific code examples. In C# development, the use of multi-threads can improve the concurrency and performance of the program. However, concurrent execution of multiple threads may also cause some problems, such as data competition and resource conflicts. To solve these problems, we need to use synchronization and mutual exclusion mechanisms to ensure correct cooperation between threads. Synchronization refers to the execution of multiple threads in a certain order to ensure the cooperative relationship between threads. Mutual exclusion means that only one thread is allowed to access a shared resource at the same time.

How to deal with multi-thread synchronization and mutual exclusion issues in C# development How to deal with multi-thread synchronization and mutual exclusion issues in C# development Oct 10, 2023 pm 03:42 PM

How to deal with multi-thread synchronization and mutual exclusion issues in C# development requires an overview of specific code examples: In C#, the use of multi-threading has become a common development requirement. However, since multiple threads operating shared resources simultaneously may cause data inconsistency or conflicts, synchronization and mutual exclusion mechanisms need to be used to solve these problems. This article will introduce how to deal with multi-thread synchronization and mutual exclusion issues in C# development, and provide specific code examples. The concept of thread synchronization When multiple threads operate shared resources at the same time, data inconsistencies or conflicts may occur.

How to solve the problem of concurrent task reordering in Go language? How to solve the problem of concurrent task reordering in Go language? Oct 09, 2023 pm 10:55 PM

How to solve the problem of concurrent task reordering in Go language? In concurrent programming, the execution order of tasks is often uncertain, which may cause some problems, especially for tasks with dependencies. In Go language, we can solve the problem of concurrent task reordering by using channels and coroutines. Below we will explain in detail how to achieve this. Typically, we use channels to achieve task synchronization and communication. In the Go language, channels can be used as a higher-level synchronization primitive to ensure the execution order of tasks. By using buffered

See all articles