/*类型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)
{
if(mtx_lock(&mutex) != thrd_success)
{
return -1;
}
++counter;
if(mtx_unlock(&mutex) != thrd_success)
{
return -1;
}
}
return 0;
}
/*在新线程中执行的减法函数。*/
int funcSubtract(void *arg)
{
for(int i=0; i<10000; ++i)
{
if(mtx_lock(&mutex) != thrd_success)
{
return -1;
}
--counter;
if(mtx_unlock(&mutex) != thrd_success)
{
return -1;
}
}
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);
}
/*连接线程。*/
if(thrd_join(threadOne, NULL) != thrd_success)
{
puts("thrd_join for threadOne failed.");
exit(EXIT_FAILURE);
}
if(thrd_join(threadTwo, NULL) != thrd_success)
{
puts("thrd_join for threadTwo failed.");
exit(EXIT_FAILURE);
}
printf("counter: %d\n", counter);
/*销毁互斥。*/
mtx_destroy(&mutex);
return 0;
}
|