CPP threads does not work on Unix-like machines!

Hi, i cannot run the following program with MSVS.NET c++, gcc on Linux or LLVM Clang on MAC. If you have any idea where it goes wrong please let me know :(

This code is taken from this page:
http://www.cplusplus.com/reference/thread/thread/thread/
-------------------------------------------

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<int> global_counter (0);

void increase_global (int n) { for (int i=0; i<n; ++i) ++global_counter; }

void increase_reference (std::atomic<int>& variable, int n) { for (int i=0; i<n; ++i) ++variable; }

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase global counter with 10 threads...\n";
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_global,1000));

  std::cout << "increase counter (foo) with 10 threads using reference...\n";
  std::atomic<int> foo(0);
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_reference,std::ref(foo),1000));

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << '\n';
  std::cout << "foo: " << foo << '\n';
  std::cout << "bar: " << bar << '\n';

  return 0;
}
Last edited on
It works if you pass a pointer instead of a reference_wrapper.

 
threads.push_back(std::thread(&C::increase_member,&bar,1000));

http://stackoverflow.com/questions/21059115/c11-thread-class-how-to-use-a-class-member-function
Thank you Peter87, I just saw that post. You are right the bug should be in the code!
Last edited on
Did you read the answer by Casey? Visual Studio is the one that has a bug. GCC and LLVM just follows how the C++ standard says it should work.
Last edited on
I think I found a clearer answer! I will post it there on stackoverflow!

http://goo.gl/W6BmcG
Last edited on
Topic archived. No new replies allowed.