Threads in C, C++, C++0x, pthread and boost
Asked Answered
M

3

8

A question about threads in C/C++...

C++0x syntax

#include <thread>

void dummy() {}

int main(int, char*[]) {
   std::thread x(dummy);
   std::thread y(dummy);
   ...
   return 0;
}

How many threads are there? Two (x and y) or three (x, y and main)? Can I call this_thread::yield() in main? And what do I get from calling this_thread::get_id() in main?

pthread syntax

#include <pthread.h>

void dummy() {}

int main(int, char*[]) {
   pthread_t x, y;
   pthread_create(&x, NULL, &dummy, NULL);
   pthread_create(&y, NULL, &dummy, NULL);
   ...
   return 0;
}

How many threads are there? Two (x and y) or three (x, y and main)? Can I call pthread_yield() in main? And what do I get from calling pthread_self() in main?

boost syntax

#include <boost/thread>

void dummy() {}

int main(int, char*[]) {
   boost::thread x(dummy);
   boost::thread y(dummy);
   ...
   return 0;
}

How many threads are there? Two (x and y) or three (x, y and main)? Can I call boost::this_thread::yield() in main? And what do I get from calling boost::this_thread::get_id() in main?

Moureaux answered 19/8, 2009 at 15:34 Comment(1)
In secound example you have written pthread_t x,t; later you use x,y; Typo I guess.Rampage
M
25

In each case you have created two additional threads so you have three (x, y, and main). You'll get a different id on each of the threads including a call in main.

Monosome answered 19/8, 2009 at 15:38 Comment(2)
It's rare when a huge question is so concisely answered.Nunnally
Not really: it's three times the same question as the boost version is an implementation of the future standard one (c++0x) that is based on the posix one...Matos
V
0

The main thread is always there and you create additional new threads. If the main thread dies you program dies or behaviour is non defined. It's also possible to start with a lot of threads as the runtime can start (and often will - like the linux_threads "pthreads" implemenation) threads on there own.

Calling yield is always possible as it just tells the os that it can give the rest of the time slice to another thread if there is any one with same or higher priority. If you don't write low level synchronization features like spinlocks there is no real reason to ever call yield in your application.

Vassell answered 26/8, 2009 at 12:26 Comment(0)
V
0

All the above three implementations give the same results. As the std::thread is implemented on top of 'pthread' so all will create three threads. Main will be your parent thread and the others will become child threads and have different IDs when each thread is created and the boost::thread is created by the same author as of std::thread but adding some enhancements.

Vivid answered 17/6, 2014 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.