pthread在类中 [英] pthread in a class

查看:181
本文介绍了pthread在类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,大家,考虑下面的代码(编译用 g ++ -lpthread thread_test.cpp )如何知道我从thread_function内部的数字线程?如果您有任何其他建议,请与我们联络。

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.

感谢!

thread_test.cpp:

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


推荐答案

可以使用pthread_self函数。

You can use pthread_self() function.

这篇关于pthread在类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆