当前位置: C语言 -- 标准库 -- <threads.h> -- mtx_destroy

mtx_destroy函数


概要:
#include <threads.h>
void mtx_destroy(mtx_t *mtx);

描述:

该函数释放参数mtx指向互斥使用的资源;如果存在等待参数mtx指向互斥的线程,函数行为是未定义的。


参数:
mtx_t *mtx

指向将被销毁的互斥的指针。


返回值:

无。


范例:
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 
/*函数mtx_destroy范例*/

/*
** 该例子假设有10000张票,
** 通过3个售票窗口出售,
** 在这里使用3个线程来实现,
** 最后统计剩余的票数和出售的票数。
*/

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

#define TICKETWINDOW 3  //售票窗口。

unsigned int ticket = 10000;  //总的票数。
unsigned int sold = 0;  //售出票数。
mtx_t mutex;

/*新线程中执行的函数。*/
int func(void *arg)
{
    unsigned int purchase;  //购票数。
    
    mtx_lock(&mutex);
    printf("Available tickets: %u\n", ticket);
    puts("Purchase tickets.");
    scanf("%u", &purchase);
    printf("Remaining tickets: %u\n\n", (ticket -= purchase));
    sold += purchase;
    mtx_unlock(&mutex);
    
    return 0;
}

int main(void)
{
    thrd_t threadId[TICKETWINDOW];
    
    /*创建互斥。*/
    if(mtx_init(&mutex, mtx_plain) != thrd_success)
    {
        perror("mtx_init error");
        exit(EXIT_FAILURE);
    }
    
    /*创建线程。*/
    for(int i=0; i<TICKETWINDOW; ++i)
    {
        if(thrd_create((threadId+i), func, NULL) != thrd_success)
        {
            perror("thrd_create error");
            exit(EXIT_FAILURE);
        }
    }
    
    /*连接线程。*/
    for(int i=0; i<TICKETWINDOW; ++i)
    {
        thrd_join(threadId[i], NULL);
    }
    
    printf("Available tickets: %u\n", ticket);
    printf("Sold tickets: %u\n", sold);
    
    /*销毁互斥。*/
    mtx_destroy(&mutex);
    
    return 0;
}


结果:

假设输入分别是123456789, 将输出:

Available tickets: 10000

Purchase tickets.

123

Remaining tickets: 9877

 

Available tickets: 9877

Purchase tickets.

456

Remaining tickets: 9421

 

Available tickets: 9421

Purchase tickets.

789

Remaining tickets: 8632

 

Available tickets: 8632

Sold tickets: 1368

注:使用Pelles C编译。


相关内容:
mtx_lock 加锁互斥的函数。
mtx_timedlock 支持超时加锁互斥的函数。
mtx_init 创建互斥的函数。
mtx_trylock 尝试加锁互斥的函数。
mtx_unlock 解锁互斥的函数。