#include <stdio.h>
#include <pthread.h>
#define LOOP_S 10
#define PRT_M 2
#define PRT_N 1
int g_flag = 0;
pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
void *thread_func(void *arg)
{
int i, j;
for (i = 0; i < LOOP_S; ++i)
{
pthread_mutex_lock(&g_lock);
while (g_flag > PRT_N - 1 || g_flag < 0)
pthread_cond_wait(&g_cond, &g_lock);
for (j = 0; j < PRT_N; ++j)
{
printf("%c", 'N');
++g_flag;
}
pthread_mutex_unlock(&g_lock);
pthread_cond_signal(&g_cond);
}
}
int main()
{
pthread_t pid;
pthread_create(&pid, NULL, thread_func, NULL);
int i, j;
for (i = 0; i < LOOP_S; ++i)
{
pthread_mutex_lock(&g_lock);
while (0 <= g_flag && g_flag < PRT_N)
pthread_cond_wait(&g_cond, &g_lock);
for (j = 0; j < PRT_M; ++j)
printf("%c", 'M');
g_flag = 0;
pthread_mutex_unlock(&g_lock);
pthread_cond_signal(&g_cond);
}
printf("\n");
pthread_join(pid, NULL);
}线程执行N次后,进程执行M次,如此循环S次
最新推荐文章于 2024-12-05 00:10:24 发布
本文介绍了一个使用C语言和POSIX线程库实现的线程同步案例,演示了如何利用互斥锁和条件变量来协调两个线程的运行顺序,确保主线程和子线程交替打印特定字符。

982

被折叠的 条评论
为什么被折叠?



