C++ 多线程

标签 c++ multithreading

<分区>

Possible Duplicate:
c++ multithread

我用c++实现了一个线程类。代码如下。 我初始化了两个对象,希望它会启动两个线程(我使用 pthread_self() 来查看线程 ID)。 但是结果显示主线程旁边只有一个线程。 我有点糊涂了……

class Thread {
public:
  int mask;
  pthread_t thread;

  Thread( int );
  void start();
  static void * EntryPoint (void *);
  void Run();
};

Thread::Thread( int a) {
  mask =a; 
}

void Thread::Run() {

  cout<<"thread begin to run" <<endl;
  cout <<" Thread Id is: "<< pthread_self() << endl; // the same thread Id.       
}

void * Thread::EntryPoint(void * pthis) {
  cout << "entry" <<endl;
  Thread *pt = (Thread *) pthis;
  pt->Run();
}

void Thread::start() {

  pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
  pthread_join(thread, NULL);
}

int main() {
  int input_array[8]={3,1,2,5,6,8,7,4};
  Thread t1(1);
  Thread t2(2);
  t1.start();  
  t2.start()
}

最佳答案

您看到此行为是因为您在生成每个线程后立即加入了它们。

当你加入一个线程时,你会阻塞直到线程终止。

关于C++ 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718503/

相关文章:

c++ - DLL 究竟何时会使用与可执行文件不同的堆?

c++ - 我的辅音/元音替换器有什么错误?

android - Kotlin 协程 - 线程切换

c++ - std::atomic<struct> 是否使所有成员也是原子的?

c# - 如何在新线程上打开一个窗口?

java - 多线程阻塞工作线程

c++ - 如何在另一个线程中创建互斥体?

C++/GLFW - 使用 Mutex 对象的正确方法?

c++ - boost::lockfree - 为排队元素调用析构函数

c++ - 我该如何表达呢?