, . , ?
:
#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;
}
If you have more than two threads, you can use a different approach. Create a structure that contains all the information a stream needs, including a pointer thisand what stream it is. Select the structure of this type, write to it everything that the stream needs, and pass it to the stream through a function pthread_createinstead of a pointer this.
source
share