mutex.c

来自「linux下的多线程调试工具」· C语言 代码 · 共 50 行

C
50
字号
#define _XOPEN_SOURCE 600#include <pthread.h>#include <stdio.h>#include <time.h>#include "alias.h"struct timespec wait = {0, 10000000};struct timespec longwait = {0, 30000000};struct timespec rem;#define WAIT nanosleep (&wait, &rem)#define LONGWAIT nanosleep (&longwait, &rem)pthread_mutex_t mutex;FILE *fd;void *func1 () {    new_thread_alias (fd, "func1");    pthread_mutex_lock (&mutex);    LONGWAIT;    pthread_mutex_unlock (&mutex);}void *func2 () {    new_thread_alias (fd, "func2");    WAIT;    pthread_mutex_lock (&mutex);    pthread_mutex_unlock (&mutex);}int main () {    pthread_t thread1, thread2;    pthread_mutexattr_t attr;    fd = alias_init ("alias");    new_thread_alias (fd, "main");    new_object_alias (fd, &mutex, "mutex");    pthread_mutexattr_init (&attr);    pthread_mutex_init (&mutex, &attr);    pthread_create (&thread1, NULL, func1, NULL);    pthread_create (&thread2, NULL, func2, NULL);    pthread_join (thread1, NULL);    pthread_join (thread2, NULL);    pthread_mutex_destroy (&mutex);    return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?