Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * pthread.cpp
- *
- * Created on: Aug 26, 2011
- * Author: jhkim
- */
- #include <iostream>
- #include <pthread.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <vector>
- using namespace std;
- void *t1(void*);
- void *t2(void*);
- void wait_sec(int _t);
- pthread_mutex_t *sync_mutex_t1;
- pthread_mutex_t *sync_mutex_t2;
- pthread_cond_t *sync_cond_t1;
- pthread_cond_t *sync_cond_t2;
- int main() {
- vector<void *(*)(void *)> thread_list;
- vector<pthread_t> tident(10);
- int threasult;
- int status;
- int i;
- sync_mutex_t1 = new pthread_mutex_t;
- sync_mutex_t2 = new pthread_mutex_t;
- sync_cond_t1 = new pthread_cond_t;
- sync_cond_t2 = new pthread_cond_t;
- pthread_mutex_init(sync_mutex_t1, NULL);
- pthread_mutex_init(sync_mutex_t2, NULL);
- pthread_cond_init(sync_cond_t1, NULL);
- pthread_cond_init(sync_cond_t2, NULL);
- thread_list.push_back(t1);
- thread_list.push_back(t2);
- #if 1
- // create thread
- for( i=0; i < thread_list.size(); i++ )
- {
- if( pthread_create(&tident[i], NULL, thread_list[i], (void *)NULL) < 0 )
- exit(0);
- }
- // wait 5 second..
- cout<<__FUNCTION__<< " wait .. " <<endl;
- wait_sec(5);
- // send signal to t1 thread
- cout<<__FUNCTION__<< " signal!! .." <<endl;
- pthread_mutex_lock(sync_mutex_t1);
- pthread_cond_signal(sync_cond_t1);
- pthread_mutex_unlock(sync_mutex_t1);
- // let's join!!
- for(i=0; i<tident.size(); i++)
- {
- pthread_join(tident[i], (void **)&status);
- }
- cout<<__FUNCTION__<< " finish!! .." <<endl;
- #endif
- return 0;
- }
- #if 1
- void *t1(void*)
- {
- cout<<__FUNCTION__<< " Start! " <<endl;
- // wait until get _cond_signal (cond_t1)
- pthread_mutex_lock(sync_mutex_t1);
- pthread_cond_wait(sync_cond_t1, sync_mutex_t1);
- pthread_mutex_unlock(sync_mutex_t1);
- // wait 5 sec ..
- wait_sec(5);
- // send signal to t2 thread
- pthread_mutex_lock(sync_mutex_t2);
- pthread_cond_signal(sync_cond_t2);
- pthread_mutex_unlock(sync_mutex_t2);
- cout<<__FUNCTION__<< " Finish! " <<endl;
- }
- void *t2(void*)
- {
- cout<<__FUNCTION__<< " Start! " <<endl;
- // wait until get _cond_signal (cond_t1)
- pthread_mutex_lock(sync_mutex_t2);
- pthread_cond_wait(sync_cond_t2, sync_mutex_t2);
- pthread_mutex_unlock(sync_mutex_t2);
- // wait 5 sec ..
- wait_sec(5);
- cout<<__FUNCTION__<< " Finish! " <<endl;
- }
- void wait_sec(int _t)
- {
- for(int i=0; i<_t; i++)
- {
- cout<< "." <<endl;
- sleep(1);
- }
- }
- #endif
Add Comment
Please, Sign In to add comment