main.cpp
#include <bits/types/struct_sched_param.h>
#include
#include
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread_1(void *);
void *thread_2(void *);
int i = 1;
int main(void) {
pthread_t t_b;
pthread_t t_a;
pthread_create(&t_a, NULL, thread_2, NULL);
pthread_create(&t_b, NULL, thread_1, NULL);
pthread_join(t_b, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
return 0;
}
void *thread_1(void *arg)
{
int err = 100;
printf(“-------------thread_1-----------\n”);
for(i = 1; i <= 20; i++)
{
printf(“thread_1: %d\n”, i);
pthread_mutex_lock(&mutex);
if (i % 3 == 0)
{
printf(“start signal!\n”);
err = pthread_cond_signal(&cond);
printf(“err = %d\n”, err);
printf(“end signal!\n”);
}
else
printf(“thread: %d\n”, i);
printf(“thread_1 is running!\n”);
pthread_mutex_unlock(&mutex);
printf("thread_1 unlock!\n");
sleep(1);
}
}
void *thread_2(void *arg)
{
int err = 200;
printf(“-------------thread_2-----------\n”);
while(i < 20)
{
pthread_mutex_lock(&mutex);
if (i % 3 != 0)
{
printf("start wait!\n");
err = pthread_cond_wait(&cond, &mutex);
printf("err = %d\n", err);
printf("end wait!\n");
}
printf("----------------thread2: %d\n", i);
pthread_mutex_unlock(&mutex);
printf("thread_2 unlock!\n");
sleep(1);
i++;
}
}
��ش�ӡ��
/workspace/CppProject/cmake-build-debug/main
-------------thread_2-----------
start wait!
-------------thread_1-----------
thread_1: 1
thread: 1
thread_1 is running!
thread_1 unlock!
thread_1: 2
thread: 2
thread_1 is running!
thread_1 unlock!
thread_1: 3
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 3
thread_2 unlock!
thread_1: 4
thread: 4
thread_1 is running!
thread_1 unlock!
start wait!
thread_1: 6
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 6
thread_2 unlock!
thread_1: 7
thread: 7
thread_1 is running!
thread_1 unlock!
start wait!
thread_1: 9
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 9
thread_2 unlock!
thread_1: 10
thread: 10
thread_1 is running!
thread_1 unlock!
start wait!
thread_1: 12
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 12
thread_2 unlock!
thread_1: 13
thread: 13
thread_1 is running!
thread_1 unlock!
start wait!
thread_1: 15
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 15
thread_2 unlock!
thread_1: 16
thread: 16
thread_1 is running!
thread_1 unlock!
start wait!
thread_1: 18
start signal!
err = 0
end signal!
thread_1 is running!
thread_1 unlock!
err = 0
end wait!
----------------thread2: 18
thread_2 unlock!
thread_1: 19
thread: 19
thread_1 is running!
thread_1 unlock!