Untitled
unknown
plain_text
4 years ago
1.5 kB
6
Indexable
#include <iostream> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <string> #include <stdlib.h> #include <queue> #include <semaphore.h> #include <cstdlib> #include <ctime> #include <sys/types.h> using namespace std; #define NUM_THREADS 8 pthread_mutex_t sharedLock = PTHREAD_MUTEX_INITIALIZER; sem_t nowDriving; int totalACount = 0, totalBCount = 0; void * thread_function(void * id){ pthread_mutex_lock(&sharedLock); char *idPointer = (char *) id; cout <<*idPointer << endl; if(*idPointer == 'A'){ totalACount++; }else if(*idPointer == 'B') { totalBCount++; } pthread_mutex_unlock(&sharedLock); //sem_wait(); if(totalACount >= 2 && totalBCount>= 2){ sem_post(&nowDriving); }else if(totalBCount >=4){ sem_post(&nowDriving); } sem_wait(&nowDriving); //sem_post(&nowDriving); } int main() { srand(time(NULL)); int teamNumA = 2; int teamNumB = 6; char team_id[NUM_THREADS]; for(int i=0; i < teamNumA; i++) team_id[i] = 'A'; for(int i=0 + teamNumA; i < teamNumB + teamNumA; i++) team_id[i] = 'B'; pthread_t threads[NUM_THREADS]; for(int i=0; i < NUM_THREADS; i++){ //if() pthread_create(&threads[i],NULL,thread_function, &team_id[i]); // sem_wait(&nowDriving); } for(int i=0; i < NUM_THREADS; i++){ pthread_join(threads[i],NULL); } return 0; }
Editor is loading...