views:

1317

answers:

2

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, t;
   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?

+20  A: 

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.

Colin Gravill
It's rare when a huge question is so concisely answered.
caspin
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...
Klaim
A: 

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.

Lothar