/*类型mtx_t范例*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
mtx_t mutex;
int counter = 0;
/*在新线程中执行的加法函数。*/
int funcAdd(void *arg)
{
for(int i=0; i<10000; ++i)
{
mtx_lock(&mutex);
++counter;
mtx_unlock(&mutex);
thrd_sleep(&(struct timespec){0, 10}, NULL);
}
return 0;
}
/*在新线程中执行的减法函数。*/
int funcSubtract(void *arg)
{
for(int i=0; i<10000; ++i)
{
mtx_lock(&mutex);
--counter;
mtx_unlock(&mutex);
thrd_sleep(&(struct timespec){0, 10}, NULL);
}
return 0;
}
int main(void)
{
thrd_t threadOne, threadTwo;
/*初始化互斥。*/
if(mtx_init(&mutex, mtx_plain) != thrd_success)
{
perror("mtx_init error");
exit(EXIT_FAILURE);
}
/*创建线程。*/
if(thrd_create(&threadOne, funcAdd, NULL) != thrd_success)
{
perror("thrd_create error");
exit(EXIT_FAILURE);
}
if(thrd_create(&threadTwo, funcSubtract, NULL) != thrd_success)
{
perror("thrd_create error");
exit(EXIT_FAILURE);
}
/*连接线程。*/
thrd_join(threadOne, NULL);
thrd_join(threadTwo, NULL);
printf("counter: %d\n", counter);
/*销毁互斥。*/
mtx_destroy(&mutex);
return 0;
}
|