已解决:
[C] 纯文本查看 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
static int count;
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cod = PTHREAD_COND_INITIALIZER;
static int nu;
void *add(void *pname){
while (1){
pthread_mutex_lock(&mut);
while (nu == 0)
pthread_cond_wait(&cod, &mut);
char *pname1 = pname;
printf("pid_or_name:%s count=%d\n", pname1, count);
pthread_mutex_unlock(&mut);
if (count > 10) {
printf("exit %s\n", pname1);
pthread_exit(NULL);
}
count ++;
sleep(1); // debug not used
}
return NULL;
}
int main(void){
int n = 4;
int i=0;
pthread_t pts[4];
char *p0 = "p0";
char *p1 = "p1";
char *p2 = "p2";
char *p3 = "p3";
for (i=0; i<n; i++){
switch (i){
case 0: pthread_create(&pts[i], NULL, add, (void *)p0); break;
case 1: pthread_create(&pts[i], NULL, add, (void *)p1); break;
case 2: pthread_create(&pts[i], NULL, add, (void *)p2); break;
case 3: pthread_create(&pts[i], NULL, add, (void *)p3); break;
default: break;
}
}
for (i=0; i<5; i++){
printf("wait nu = 1\n");
nu = 1;
pthread_cond_broadcast(&cod);
sleep(1);
printf("wait nu = 0\n");
nu = 0;
sleep(1);
}
for (i=0; i<n; i++){
printf("join:%d\n", i);
pthread_join(pts[i], NULL);
}
pthread_mutex_destroy(&mut);
pthread_cond_destroy(&cod);
exit(0);
}
[C] 纯文本查看 复制代码 wait nu = 1
pid_or_name:p1 count=0
pid_or_name:p0 count=1
pid_or_name:p2 count=2
pid_or_name:p3 count=3
wait nu = 0
wait nu = 1
pid_or_name:p2 count=4
pid_or_name:p0 count=5
pid_or_name:p1 count=6
pid_or_name:p3 count=7
wait nu = 0
wait nu = 1
pid_or_name:p1 count=8
pid_or_name:p2 count=9
pid_or_name:p0 count=10
pid_or_name:p3 count=11
exit p3
pid_or_name:p1 count=11
exit p1
wait nu = 0
wait nu = 1
pid_or_name:p0 count=11
exit p0
pid_or_name:p2 count=11
exit p2
wait nu = 0
wait nu = 1
wait nu = 0
join:0
join:1
join:2
join:3
|