⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 example91.c

📁 Linux网络编程教程适合初学者入门学习
💻 C
字号:
/* example91.c */

#include	<stdio.h>

#include	<stdlib.h>

#include	<pthread.h>

#include	<errno.h>



#define		MAXNITEMS	1000000

#define		MAXNTHREADS	100



#define min(a,b)        ((a) < (b) ? (a) : (b))



int	nitems;

struct {

	pthread_mutex_t	mutex;

	int		buff[MAXNITEMS];

	int		nput;

	int		nval;

}shared = {

	PTHREAD_MUTEX_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]);

	}

	Pthread_create(&tid_consume, NULL, consume, NULL);

	for (i=0; i<nthreads; i++) {

		Pthread_join(tid_produce[i], NULL);

		printf("count[%d] = %d\n", i, count[i]);

	}

	Pthread_join(tid_consume, NULL);

	exit(0);

}

void *

produce(void *arg)

{

	for( ; ; ) {

		pthread_mutex_lock(&shared.mutex);

		if (shared.nput >= nitems) {

			pthread_mutex_unlock(&shared.mutex);

			return(NULL);

		}

		shared.buff[shared.nput] = shared.nval;

		shared.nput++;

		shared.nval++;

		pthread_mutex_unlock(&shared.mutex);

		*((int *)arg) += 1;

	}

}

void

consume_wait(int i)

{

	for ( ; ; ) {

		pthread_mutex_lock(&shared.mutex);

		if (i < shared.nput) {

			pthread_mutex_unlock(&shared.mutex);

			return;

		}

		pthread_mutex_unlock(&shared.mutex);

	}

}

void *

consume(void *arg)

{

	int	i;

	for (i=0; i<nitems; i++) {

		consume_wait(i);

		if (shared.buff[i] != i)

			printf("buff[%d] = %d\n", i, shared.buff[i]);

	}

	return(NULL);

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -