semaphore

semaphore - { cout<<"\n ERROR creating thread...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <iostream> # using namespace std; u #define NITER 1000000 # int Count=0; i sem_t binarySem; /* Use as a mutex */ / void * ThreadAdd(void * a) { int i, tmp; for(i = 0; i < NITER; i++) { sem_wait(&binarySem); tmp = ++Count; sem_post(&binarySem); if (!(tmp % 100000)) { cout<<endl<<"Thread"<<*(int *)a<<"\tcount value = "<<tmp; } } } int main(int argc, char * argv[]) { pthread_t tid1, tid2; int id1=1, id2=2; { cout<<"\n Error initialize the semaphore"; exit(1); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { cout<<"\n ERROR creating thread 1"; exit(1); } if(pthread_create(&tid2, NULL, ThreadAdd, (void *)&id2)) { cout<<"\n ERROR creating thread 2"; exit(1); } if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */ { cout<<"\n ERROR joining thread"; exit(1); } if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */ { cout<<"\n ERROR joining thread"; exit(1); } if (Count < 2 * NITER) cout<<"\n BOOM! count is "<<Count<<", should be "<<2*NITER<<"."<<endl; else cout<<"\n OK! count is "<<Count<<endl; sem_destroy(&binarySem); pthread_exit(NULL); }...
View Full Document

This note was uploaded on 12/01/2010 for the course CS 2342 taught by Professor Dr during the Spring '10 term at HKU.

Page1 / 2

semaphore - { cout<<"\n ERROR creating thread...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online