
若干 个汽车 参数 1 等待 若干个窗口处理 参数2, 然后进行锁操作后对共享内存进行写入。
- #include<sys/sem.h>
- #include<sys/types.h>
- #include<sys/ipc.h>
- #include<stdio.h>
- #include<sys/stat.h>
- #include<pthread.h>
- #include<stdlib.h>
- #include <sys/shm.h>
- #define MAXNITEMS 1000000
- #define MAXNTHREADS 100
- #define min(a,b)((a) < (b) ? (a) : (b))
- #define max(a,b)((a) > (b) ? (a) : (b))
- int nitems;
- char *pmat = NULL;
- char tempbuff[16];
- struct{
-
- pthread_mutex_t mutex;
- char buff[200][MAXNITEMS];
- int nput;
- int nval;
- }shared={PTHREAD_MUTEX_INITIALIZER};
- void *enregistrer(void *),*taiter(void *);
- int main(int argc,char **argv){
-
- int i,nthreads,count[MAXNTHREADS];
- pthread_t tid_produce[MAXNITEMS],tid_consume;
- int id_of_shmid;
- int j;
-
- if(argc!=3) {
- printf("un grave problem sur le num de argument/n");
- exit (-1);
- }
-
-
- nitems = min(atoi(argv[1]),MAXNITEMS);
-
- nthreads=min(atoi(argv[2]),MAXNTHREADS);
-
- id_of_shmid = shmget(0x1234, nitems*100, 0666|IPC_CREAT);
-
-
- pmat = (char *)shmat(id_of_shmid, 0, 0);
-
- pthread_setconcurrency(nthreads+1);
- for (i = 0; i < nthreads; i++) {
- count[i] = 0;
- pthread_create(&tid_produce[i], NULL, enregistrer, &count[i]);
- }
-
- pthread_create(&tid_consume,NULL,taiter,NULL);
- for (i = 0; i < nthreads; i++) {
- pthread_join(tid_produce[i], NULL);
- printf("Guichet[%d] traite %d voitures. /n", i, count[i]);
- }
- pthread_join(tid_consume, NULL);
-
- printf("---------------matricule--------------------/n");
-
- for (j = 0; j < nitems; j++) {
-
- printf("ID de traitement: %s/n",pmat+j*100);
-
- }
- printf("---------------------------------------------/n");
-
-
- shmdt(pmat);
- exit(0);
-
- }
- void *
- enregistrer(void *arg){
- for ( ; ; ) {
- sleep(1);
- pthread_mutex_lock(&shared.mutex);
- if (shared.nput >= nitems) {
- pthread_mutex_unlock(&shared.mutex);
- return(NULL);
- }
-
- sprintf(shared.buff[shared.nput],"%d",shared.nput);
-
- strcat(shared.buff[shared.nput],"00TP300"),
- shared.nput++;
- shared.nval++;
- pthread_mutex_unlock(&shared.mutex);
- *((int *) arg) += 1;
- }
- }
- void *
- taiter(void *arg){
- int i;
- for (i = 0; i < nitems; i++) {
- taiter_wait(i);
-
-
-
- printf("C'est le numero de [%d] voitrue et son numero de matricule est %s/n", i,shared.buff[i]);
-
- memcpy(pmat+i*100, shared.buff[i], 100);
- }
- return(NULL);
- }
- void
- taiter_wait(int i){
- for ( ; ; ) {
- pthread_mutex_lock(&shared.mutex);
- if (i < shared.nput) {
- pthread_mutex_unlock(&shared.mutex);
- return;
- }
- pthread_mutex_unlock(&shared.mutex);
- }
- }