File: threads.cpp

package info (click to toggle)
kdevelop 4%3A4.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 18,844 kB
  • sloc: cpp: 91,758; python: 1,095; lex: 422; ruby: 120; sh: 114; xml: 42; makefile: 38
file content (64 lines) | stat: -rw-r--r-- 1,286 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* This is a test program for KDevelop GDB debugger support.

   There are two worker threads, they are programmed to call
   the 'foo' function in strictly interleaved fashion.
*/

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

int schedule[] = {1, 2};
int schedule_size = sizeof(schedule)/sizeof(schedule[0]);
int index = 0;
int exit = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

void foo(int thread, int i)
{
    printf ("hi there, from thread %d on iteration %d\n", thread, i);
}

void runner(int id)
{
    for(int i = 0; i < 1000000 && !exit; ++i)
    {
        pthread_mutex_lock(&mutex);

        while (schedule[index] != id) {
            pthread_cond_wait(&condition, &mutex);
        }

        foo(id, i);
        
        ++index;
        if (index >= schedule_size)
            index = 0;
               
        pthread_cond_broadcast(&condition);
        pthread_mutex_unlock(&mutex);

        sleep(1);
    }
}

void* thread(void* p)
{
    runner((int)p);
    return NULL;
}

int main()
{
    pthread_t p1, p2;
    
    pthread_create(&p1, 0, &thread, (void*)1);
    pthread_create(&p2, 0, &thread, (void*)2);    
    
    pthread_join(p1, 0);
    pthread_join(p2, 0);
    
    return 0;
}