?? example92.c
字號:
/* example92.c */
#include <pthread.h>
#include <errno.h>
#define MAXNITEMS 1000000
#define MAXNTHREADS 100
#define min(a,b) ((a) < (b) ? (a) : (b))
int nitems;
int buff[MAXNITEMS];
struct {
pthread_mutex_t mutex;
int nput;
int nval;
}put = {
PTHREAD_MUTEX_INITIALIZER
};
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
}nready = {
PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER
};
void *produce(void *);
void *consume(void *);
void
Pthread_create(pthread_t *tid, const pthread_attr_t *attr,
void * (*func)(void *), void *arg)
{
int n;
if ( (n = pthread_create(tid, attr, func, arg)) == 0)
return;
errno = n;
printf("pthread_create error");
}
void
Pthread_join(pthread_t tid, void **status)
{
int n;
if ( (n = pthread_join(tid, status)) == 0)
return;
errno = n;
printf("pthread_join error");
}
int
set_concurrency(int level)
{
#ifdef HAVE_THR_SETCONCURRENCY_PROTO
int thr_setconcurrency(int);
return(thr_setconcurrency(level));
#else
return(0);
#endif
}
void
Set_concurrency(int level)
{
if (set_concurrency(level) != 0)
printf("set_concurrency error");
}
int
main(int argc, char **argv)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_produce[MAXNTHREADS], tid_consume;
if (argc != 3) {
printf("usage: prodcons3 <#items> <#threads>\n");
return 0;
}
nitems = min(atoi(argv[1]), MAXNITEMS);
nthreads = min(atoi(argv[2]), MAXNTHREADS);
set_concurrency(nthreads + 1);
for (i=0; i<nthreads; i++) {
count[i] = 0;
Pthread_create(&tid_consume, NULL, produce, &count[i]);
}
for (i=0; i<nthreads; i++) {
Pthread_join(tid_produce[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
}
Pthread_create(&tid_consume, NULL, consume, NULL);
Pthread_join(tid_consume, NULL);
exit(0);
}
void *
produce(void *arg)
{
for( ; ; ) {
pthread_mutex_lock(&put.mutex);
if (put.nput >= nitems) {
pthread_mutex_unlock(&put.mutex);
return(NULL);
}
buff[put.nput] = put.nval;
put.nput++;
put.nval++;
pthread_mutex_unlock(&put.mutex);
pthread_mutex_lock(&nready.mutex);
if (nready.nready == 0)
pthread_cond_signal(&nready.cond);
nready.nready++;
pthread_mutex_unlock(&nready.mutex);
*((int *)arg) += 1;
}
}
void *
consume(void *arg)
{
int i;
for (i=0; i<nitems; i++) {
pthread_mutex_lock(&nready.mutex);
while (nready.nready == 0)
pthread_cond_wait(&nready.cond, &nready.mutex);
nready.nready--;
pthread_mutex_unlock(&nready.mutex);
if (buff[i] != i)
printf("buff[%d] = %d\n", i, buff[i]);
}
return(NULL);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -