pthread в классе

2 ответа

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

3
ответ дан 14 December 2019 в 19:19
поделиться

Я понял, что могу это сделать, но не уверен, что лучше всего сделать статические переменные 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;
}
1
ответ дан 14 December 2019 в 19:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: