Search code examples
c++multithreadingc++11pthreadsboost-thread

Threads in C, C++, C++0x, pthread and boost


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?


Solution

  • 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.