нить в классе - PullRequest
       13

нить в классе

5 голосов
/ 12 сентября 2009

Привет всем, учитывая следующий код (скомпилированный с g++ -lpthread thread_test.cpp), как я могу узнать, какой номер потока у меня внутри "thread_function"? И дайте мне знать, если у вас есть другие предложения.

Спасибо! * * 1004

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;
}

Ответы [ 3 ]

3 голосов
/ 12 сентября 2009

Вы можете использовать функцию pthread_self ().

1 голос
/ 27 августа 2011

Правильный ответ во многом зависит от того, зачем вам нужна эта информация. Если два потока делают разные вещи, почему у них одинаковая функция запуска?

Одно простое исправление таково:

#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, int which );
      static void* thread_function_1( void *ptr );
      static void* thread_function_2( 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_1, this );
   int ret2 = pthread_create( &m_thread2, NULL, &A::thread_function_2, this );
}

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

void* A::thread_function_1( void *ptr ) { thread_function(ptr, 1); }
void* A::thread_function_2( void *ptr ) { thread_function(ptr, 2); }

void* A::thread_function( void *ptr, int which ) { 
   printf( "I'm thread %d\n", which );

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

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

   return 0;
}

Если у вас более 2 потоков, вы можете использовать другой подход. Создайте структуру, которая содержит всю информацию, необходимую потоку, включая указатель this и какой это поток. Выделите структуру такого типа, заполните ее всем, что нужно потоку, и передайте ее потоку через функцию pthread_create вместо только указателя this.

1 голос
/ 12 сентября 2009

Ну, я понял, что могу это сделать, но я не уверен, что лучше сделать статические переменные pthread_t. Мнения?

#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;
}
...