gpt4 book ai didi

c++ - C++ 中的多线程示例

转载 作者:行者123 更新时间:2023-11-28 06:56:37 25 4
gpt4 key购买 nike

目前,我正在研究一个示例,其中我在 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

据我所知,我应该能够让 2 个线程在顶部并行运行。请帮助我,因为我是多线程的新手。

最佳答案

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com