Search notes:

C++ Standard Library: accesssing shared variables in threads

//
//  g++ -std=c++11 read-write-in-threads.cpp -l pthread
//
#include <atomic>
#include <thread>
#include <iostream>

            unsigned long long  ull  ;
std::atomic<unsigned long long> ull_a;

void T() {

  for (int i=0; i<1000000; i++) {
    ull  ++;
    ull_a++;
  }

}

int main () {

  ull   = 0;
  ull_a = 0;

  std::thread t1(T);
  std::thread t2(T);
  std::thread t3(T);
  std::thread t4(T);
  std::thread t5(T);

  t1.join();
  t2.join();
  t3.join();
  t4.join();
  t5.join();

  std::cout << "ull:   " << ull   << std::endl;
  std::cout << "ull_a: " << ull_a << std::endl;

}
Github repository about-cpp-standard-library, path: /atomic/read-write-in-threads.cpp
The program might print:
ull:   1991703
ull_a: 5000000

See also

C++ Standard Library

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758193900, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/C-C-plus-plus/CPP-Standard-Library/atomic/read-write-in-threads(82): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78