pthreads newby issues

Hi,
I have run this example, and I'm not getting the expected result.

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
#include <pthread.h>
    #include <stdio.h>

    #define it 2

    pthread_t threads[it];

    pthread_mutex_t mu;

    void *thread_func(void *arg){
      int i = *(int *) arg;
      pthread_mutex_lock(&mu);
      printf("thread---  %d\n", i);

      pthread_mutex_unlock(&mu);
    }

    void main(){
      int i;
      pthread_mutex_init(&mu,NULL);


      int vec[it];
      for(i=0; i<it; i++)
        vec[i]=i;

      for (i=0; i<it; i++)
        pthread_create(&(threads[i]), NULL, thread_func, &i);


      for (i=0; i<it; i++)
        pthread_join(threads[i], NULL);

    }


When I run this code, it shows me random results. For example, I can get

thread--- 1
thread--- 0

or
thread--- 0
thread--- 0

I tried locking the printf function, as shown in the example, to no avail. But if I change the line

 
       pthread_create(&(threads[i]), NULL, thread_func, &i);


by this
 
        pthread_create(&(threads[i]), NULL, thread_func, &vec[i]);

I always get the intended result (even with locks removes) that is

thread--- 1
thread--- 0

or this

thread--- 0
thread--- 1

What is the problem with the original code?

thanks in advance!


When 11 is executed it will read the value of i from main, but you don't know when this will happen so you don't know what the value is going to be.
This is what I thought, but since i is assigned before the thread is created i still found the output

thread--- 0
thread--- 0

strange.
Last edited on
It's not strange. You set i to 0 again in the last loop.
Last edited on
I see. Thanks!!
Hi,
That is a nice thread.

I have a question, where is the mutex being locked by each thread?

I only see it getting unlocked by each thread.

Thank you.

BTW, where did you gain that Linux knowledge?

I'm trying to get into Operating Systems world, and into Linux specifically.
Topic archived. No new replies allowed.