C++中的多线程示例

Example for multithreadig in C++

本文关键字:多线程 C++      更新时间:2023-10-16

Currenly我正在研究一个在C++中使用多读的例子。

#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS     2
void *PrintHello(void *threadid) 
{
     long tid;
     tid = (long)threadid;
     for (int i =0; i < 20000000000; i++)
     {
        int x;
        x=x+x*x;
     }
     cout << "Hello World! Thread ID, " << tid << endl;
     pthread_exit(NULL);
 }
 int main ()
 {
     pthread_t threads[NUM_THREADS];
     int rc;
     int i;
     for( i=0; i < NUM_THREADS; i++ ){
        cout << "main() : creating thread, " << i << endl;
     rc = pthread_create(&threads[i], NULL, 
                      PrintHello, (void *)i);
     if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
     }
  }
  pthread_exit(NULL);
}

但由于我电脑上的核心数量是2,所以我应该在使用top时获得2个线程。

  ./multithreadprogram 
   main() : creating thread, 0
   main() : creating thread, 1

但在顶部,我只看到一个

  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND                                                                                                           
  13316 manish    20   0     0    0    0 Z 196.6  0.0   0:16.95 multithreadprog                                                                                                   
  3629 manish    20   0  528m  25m  12m S   0.7  0.3   0:32.57 gnome-terminal  

据我所知,我应该能够让两个三分球在上面平行运行。请帮帮我,因为我是多线程的新手。

注意进程表中的196%CPU,这意味着您的程序在多个内核中运行;)