File indexing completed on 2024-05-26 04:43:14

0001 /* This is a test program for KDevelop GDB debugger support.
0002 
0003    There are two worker threads, they are programmed to call
0004    the 'foo' function in strictly interleaved fashion.
0005 */
0006 
0007 #include <pthread.h>
0008 #include <stdio.h>
0009 #include <unistd.h>
0010 
0011 int schedule[] = {1, 2};
0012 int schedule_size = sizeof(schedule)/sizeof(schedule[0]);
0013 int index = 0;
0014 int exit = 0;
0015 
0016 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
0017 pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
0018 
0019 void foo(int thread, int i)
0020 {
0021     printf ("hi there, from thread %d on iteration %d\n", thread, i);
0022 }
0023 
0024 void runner(int id)
0025 {
0026     for(int i = 0; i < 1000000 && !exit; ++i)
0027     {
0028         pthread_mutex_lock(&mutex);
0029 
0030         while (schedule[index] != id) {
0031             pthread_cond_wait(&condition, &mutex);
0032         }
0033 
0034         foo(id, i);
0035         
0036         ++index;
0037         if (index >= schedule_size)
0038             index = 0;
0039                
0040         pthread_cond_broadcast(&condition);
0041         pthread_mutex_unlock(&mutex);
0042 
0043         sleep(1);
0044     }
0045 }
0046 
0047 void* thread(void* p)
0048 {
0049     runner((int)p);
0050     return NULL;
0051 }
0052 
0053 int main()
0054 {
0055     pthread_t p1, p2;
0056     
0057     pthread_create(&p1, 0, &thread, (void*)1);
0058     pthread_create(&p2, 0, &thread, (void*)2);    
0059     
0060     pthread_join(p1, 0);
0061     pthread_join(p2, 0);
0062     
0063     return 0;
0064 }