C++中的多线程示例
Example for multithreadig in C++
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,这意味着您的程序在多个内核中运行;)
相关文章:
- 在C++中使用cURL和多线程
- 多线程双缓冲区
- 为什么我的多线程作业队列崩溃
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 为什么一个向量上的多线程操作很慢
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 全局变量 多读取器 一个写入器多线程安全?
- boost::文件系统::recursive_directory_iterator多线程安全
- 如何阻止TensorFlow的多线程
- 如何在多线程中正确使用unique_ptr进行多态性?
- 并发/多线程:是否可以以这种方式生成相同的输出?
- sigwait() 在多线程程序中不起作用
- 多线程程序中出现意外的内存泄漏
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 多线程比没有线程C++慢
- 具有 C++11 多线程的特征库
- 通过安装信号处理程序关闭多线程应用程序
- 成员变量在多线程 C++ 时自行更改
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误