views:

386

answers:

2

Hey everyone, considering the following code (compiled with g++ -lpthread thread_test.cpp) how can I know what number thread I am in from inside "thread_function"? And let me know if you have any other suggestions.

Thanks!

thread_test.cpp:

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

class A { 
   public:
      A();
      void run();

   private:
      static void* thread_function( void *ptr );
      pthread_t m_thread1, m_thread2;

      static int m_global;
};

int A::m_global = 0;

A::A() {
   int ret1 = pthread_create( &m_thread1, NULL, &A::thread_function, this );
   int ret2 = pthread_create( &m_thread2, NULL, &A::thread_function, this );
}

void A::run() {
   while ( 1 ) { 
      printf( "parent incrementing...\n" );
      m_global++;
      sleep( 2 );
   }   
}

void* A::thread_function( void *ptr ) { 
   printf( "I'm thread ?\n" );

   while ( 1 ) { 
      printf("thread global: %d\n", m_global );
      sleep( 1 );
   }   
}

int main() {
   A a;
   a.run();

   return 0;
}
+2  A: 

You can use pthread_self() function.

danadam
ok i see that now... should i use something like pthread_key_create to store some kind of thread specific data in it to identify whether it is thread 1 or 2 then? I'm trying to figure out if pthread_key_create is really what I want...
You could use thread specific variable but I don't think it's necessary. Just call pthread_self() whenever you want to use current thread number.
danadam
A: 

Well i figured out I could do this, but I'm not sure if making the pthread_t variables static is the best thing to do. Opinions?

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

class A { 
   public:
      A();
      void run();

   private:
      static void* thread_function( void *ptr );
      static pthread_t m_thread1, m_thread2;

      static int m_global;
};

int A::m_global = 0;
pthread_t A::m_thread1 = 0;
pthread_t A::m_thread2 = 0;

A::A() {
   int ret1 = pthread_create( &m_thread1, NULL, &A::thread_function, this );
   int ret2 = pthread_create( &m_thread2, NULL, &A::thread_function, this );
}

void A::run() {
   while ( 1 ) { 
      printf( "parent incrementing...\n" );
      m_global++;
      sleep( 2 );
   }   
}

void* A::thread_function( void *ptr ) { 
    int thread_num = 0;
    if ( pthread_self() == m_thread1 ) {
        thread_num = 1;
    } else {
        thread_num = 2;
    }

    printf( "I'm thread %d\n", thread_num );

    while ( 1 ) { 
        printf("thread %d global: %d\n", thread_num, m_global );
        sleep( 1 );
    }   
}

int main() {
   A a;
   a.run();

   return 0;
}