简体   繁体   中英

Threading in C++ using std::thread

I'd like to know if I initialize four std::thread 's, will this crash a dual thread cpu or are std::thread 'sa virtual thread kind of thing.

I mainly want to know because a program I am writing for class would go much faster with four threads, but I have no idea how many threads my grader has on their CPU. Mine has 8 but hers could easily have 2. I don't want to crash her system, so any help would be

I'm fairly new to Computer Science so I welcome any help I can get.

The number of threads doesn't have to be limited to the number of cores. The OS will just schedule the threads as cores become available.

That said, you can use hardware_concurrency() to find you how many cores/processors are available, and base the number of threads you use on that.

... if I initialize four std::thread 's, will this crash a dual thread cpu

I suspect you are asking about threads vs cores ... threads are independent of core's. A single core cpu can run many threads.

  • N threads, where N > core-count, will not crash a Linux system.

Linux provides a special file. I use a home grown version of grep in my C++ programs to read and count how many lines of this special file have the string "processor" in them.

//       The special file of Ubuntu -- vvvvvvvvvvvvv
size_t retVal = DTB::grep(std::string("/proc/cpuinfo"),
                          std::string("processor"),  // line count of "processor" is core count
                         nullDev); // dev/null -- no output

This invocation returns the count of processors. My old Dell has 2.


The first few lines of the file look like:

$ cat /proc/cpuinfo
processor   : 0
vendor_id   : AuthenticAMD
cpu family  : 15
model       : 75
model name  : AMD Athlon(tm) 64 X2 Dual Core Processor 5000+
stepping    : 2
cpu MHz     : 1000.000
cache size  : 512 KB

The command top shows I have > 178 tasks in state running or sleeping, a lot more than 2.


would go much faster with four threads,

I suspect it would, but this is not guaranteed. This is yet another test the developer must perform to confirm your guess. When the threads interact with each other (semaphores? messaging?) it becomes increasingly unlikely that you (or I) can predict the results.


So its not worth it to make it quad threaded?

I think you should measure the performance of both forms of your code on your machine. If 4 threads are quicker, it is not your fault that the other machine is slower.

I recommend planning on recording duration times ... perhaps make it part of the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM