multithreading,c++11,atomic,stdatomic , Read a variable in another thread

Read a variable in another thread


Tag: multithreading,c++11,atomic,stdatomic

I'm using linux and I have two variable that is read/write in another thread. Once in a while (100ms) ThreadB reads the status of the variables and does something. It's basically a while(1){ dosomething(); usleep(); }. I'm worried the variables will be cached and never updated.

What's the best way to ensure the loop will work after optimizations? I am thinking volatile should do the job but I hear it doesn't work sometimes. Both loops don't run frequently (10ms+). What's the most simple and straightforward way to access them? I'm using C++11

I'm a little unsure how to use std::atomic<int>. Can I just use it like a normal int variable and it will work as expected?


You can indeed just declare it as std::atomic<int>, and things should work as you want.

volatile is about preserving the sequence of addresses and values that the generated code must present to the processor for reading/writing. It doesn't at all constrain what the hardware does with that for purposes of memory consistency, which is the concern of atomic. Here's an article from Intel explaining this difference.

The C and C++ standards (from 2011 onwards) define a memory model that describes what operations are or aren't defined according to the language, and what values an expression can produce if the program as a whole is well-defined.

According to the standards, any program doing unsynchronized access by multiple threads to a single object (e.g. your shared int), in which at least once access is a write, is undefined. Declaring a variable volatile doesn't make accesses to it synchronized. Accesses to variables declared as atomic are always synchronized, by definition.

In the default case, if you just use atomic<int> without changing anything else about how you use it, you'll get what are known as sequentially consistent accesses, which are the most strongly coordinated between threads, and hence potentially most costly. For your use case, that doesn't seem to be a concern - the cost is on the order of nanoseconds to microseconds, while you're polling in milliseconds. If you did need to optimize further, you could potentially specify less restrictive accesses.


C++11 Allocation Requirement on Strings

I had heard that C++11 was going to require strings to be allocated in contiguous memory. I even thought I saw a stack overflow question on it, but I can't seem to find it. I know that in practice both gcc and Visual Studio do allocate strings contiguously, I'm just...

Sorting vector of Pointers of Custom Class

I have vector<FPGA*> current_generation_, which I'd like to sort by FPGA member fitness_ using the sort_members function. Applicable code follows: bool sort_members (FPGA* fpga_first, FPGA* fpga_second) { return (fpga_first->fitness() < fpga_second->fitness()); }; fpga.hpp #include <vector> class FPGA { public: explicit FPGA(int input_gates, int output_gates, int normal_gates); const int fitness(); protected:...

Call to implicitly-deleted copy constructor in LLVM(Porting code from windows to mac)

We are in the process of porting some c++ code from windows to mac and are having issues compiling it with LLVM 6.1 using c++11. We are encountering errors all over the place of "Call to implicitly-deleted copy contructor" Some of these errors are popping up in our code. for...

C++ error: deduced conflicting types for parameter 'T' string vs const char *

So, I am writing a simple, templated search function for deque container. Here's the code: template <typename T> void searchInDequeFor(std::deque<T> Deque, T searchValue) { for(const auto & element : Deque) { if(Deque.empty()) { std::cout << "Deque is empty, nothing to search for..." << "\n"; } else if(element==searchValue) { std::cout <<...

How to re-write templated function to handle type deduction

So, I have this search function for the map container: template <typename Key, typename T> void searchInMapByKey(std::map<Key,T> Map, T keyValue) { if(Map.empty()) { std::cout << "Map is empty, nothing to search for..." << "\n"; } else { for(const auto & element : Map) { if(element.first==keyValue) { std::cout << keyValue <<...

Why is initialization of enum class temporaries with arbitrary values allowed?

I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal: enum class Foo { Bar }; Foo const v1 = Foo(5); The question is: why does this...

“Emulating” std::declval issues. Works (kind of) in g++, fails to compile in clang++

Trying to better understand std::declval, I came up with the following "toy model" code: #include <iostream> #include <typeinfo> struct Bar { Bar(double); // some non-default ctor double f(); // some function of which return type we want to get }; using Barref = Bar&&; // emulating std::declval<Bar>() int main() {...

performance issues executing list of stored procedures

I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...

Atomic/not-atomic mix, any guarantees?

Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

Is executing C++ code in comments with certain Unicode characters allowed, like in Java?

I know that executing Java code in comments with certain Unicode characters is allowed. Please see this question for further clarification Executing Java code in comments. So was just curious to know if C++ has such features?

Multiple Threads searching on same folder at same time

Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

How can I simulate a nested function without lambda expressions in C++11?

I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot));; return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

C++ why does SFINAE fail with only a class template parameter?

I'm using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls operator[](int) const first, and if that doesn't exist then operator()(int) const: template<int I> struct rank : rank<I-1> { static_assert(I > 0,...

No match for 'operator*' error

Hello fellow programmers! I was going to write a small program for calculating total pay for different periods of time depending on the amount of hours and the salary that the user enters. I managed to make a small bit of the program but when I try to run it...

std::move on a C++ class does not move all members?

I understand that using v.push_back(std::move(foo)) will move foo contents to a vector. However I do not understand why the below code : #include <iostream> #include <vector> struct Foo { std::string s; float f; friend std::ostream& operator<<(std::ostream& stream,const Foo& foo) { stream << "{" << foo.s << ":" << foo.f <<...

Implicit use of initializer_list

§[dcl.init.list] 8.5.4/2: The template std::initializer_list is not predefined; if the header <initializer_list> is not included prior to a use of std::initializer_list — even an implicit use in which the type is not named ( — the program is ill-formed. Does that mean this program is ill-formed? #include <vector> int main()...

Set Label From Thread,multithreading,winforms
Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

Same function with and without template

I am trying to understand a piece of code of C++11. A class contains 2 functions as shown below: class abc { public: void integerA(int x); template<typename typ> void integerA(typ x); }; I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?...

Dereferencing a temporary unique_ptr

unique_ptr<A> myFun() { unique_ptr<A> pa(new A()); return pa; } const A& rA = *myFun(); This code compiles but rA contains garbage. Can someone explain to me why is this code invalid? Note: if I assign the return of myFun to a named unique_ptr variable before dereferencing it, it works fine....

java multithreading start() and run() [duplicate]

This question already has an answer here: Java: What's the difference between Thread start() and Runnable run() 10 answers Below is my Multithreading class: public class Multithreading extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e); } System.out.println(i); } } public static void main(String args[]) {...

Java how to limit number of threads acting on method

I have java method in my web application doing heavy file operation. The thing is, if more than 5 threads come simultaneously (which will come in testing phase) it breaks down. I mean it cannot handle heavy traffic. That's why I want to handle maximum 5 requests at a time...

How can we make a thread to sleep for a infinite time in java?

Pls help me to understand how can we make a thread to sleep for a infinite time period .

Type function that returns a tuple of chosen types

I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

C++ operator []

I am trying to implement the operator [] that is to be used once for Set and once as Get, i need to differentiate between the two cases, as in the case of get, i need to throw an exception if the returned value is equal to -1; whereas in...

Invoke form showdialog is not modal,multithreading,invoke
I have 2 forms, 1 MainForm and 1 Form2. I am trying to display Form2 as a modal form and background from MainForm. Here's what I have so far. The default MainForm appears and after 5 seconds it will show Form2 as a Modal form from a background thread. I...

Call template function for the value of a pointer out of a template function, in C++

I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Looking to pause a thread using thread.sleep

I am using a mouse listener for mouse pressed and released. When the mouse is pressed I want to have a counter incrementing a variable, and when the mouse is released I want to decrement that variable. Right now, my code is working and does that but the increment is...

Calling dispatch_sync from a concurrent queue - does it block entirely?

Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

Any way to catch an exception occurring on a thread I don't own?

I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own...

How can I know the lock information in java?

Is there any tool or way that can get all the information about the locks in java? for example, if there is a java program, it creates two threads, and both threads require locks for some variable. Is there any tools that can output the information like which thread locks...

Java 5 Multi threading, catch thread exceptions

I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

Passing something as this argument discards qualifiers

Using the below code, i get the following compile error: In static member function ‘static std::string ctedata::Record::getDispatcher<std::basic_string<char> >::impl(const ctedata::Record&, const string&)’: /home/jason/CrownTheEmpire/lib/ctedata/data.h:111:38: error: passing ‘const std::map<std::basic_string<char>, std::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] return rec.fieldValues_[field]; ^ In file included from /usr/include/c++/5.1.0/map:61:0, from...

Does wait() need synchronization on local variable

I had this code (which was working fine): public static void runOnUiThread(Activity c, final Runnable action) { // Check if we are on the UI Thread if (Looper.getMainLooper() == Looper.myLooper()) { // If we are, execute immediately; return; } // Else run the runnable on the UI Thread and...

What happens if all node.js's worker threads are busy

I try to understand how node.js works and although I have read this article: When is the thread pool used? I am not sure what happens if all worker threads are busy and another async I/O operation is ready to be executed. If I got this article right, the...

Images not appearing on WPF form when loading asynchronously

I'm attempting to display (in a ListBox with a custom DataTemplate) a series of BitmapSource frames (thumbnails) extracted from a multi-page tiff image. When I process the tiff on the UI thread, and either directly add the images to a listbox's item collection or add them to a bound ObservableCollection,...

Is there standard implementation for thread block/resume in java SE?

I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple. Is there any ready to use solution? Preferably in java SE 6? Or do I have to...

wait for an event regulary

In a program I need to wait for an event (keypress) and get it's char. after that program will continue. this progress will Repeat several time. in my first try, codes run and any character did not save. I find out I should use threading but I am not Familiar...

How can I convert an int to a string in C++11 without using to_string or stoi?

I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

In c++11 what should happen first: raw string expansion or macros?

This code works in visual c++ 2013 but not in gcc/clang: #if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

I know you would deadlock by doing this on a serial queue, but I haven't found anything that mentions deadlocking by doing it on a concurrent queue. I just wanted to verify it wont deadlock (it doesn't seem like it would, as it would only block one of the threads...

Can't compile C++11 source using GCC 5.1 toolchain

I'm trying to compile a library written with C++11 features using GCC 5.1 on Ubuntu. However, it complains std::unique_ptr is not defined. gcc (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 g++ (Ubuntu 5.1.0-0ubuntu11~14.04.1) 5.1.0 CXX flags: -std=c++11 -Wall -Wextra -Weffc++ -pedantic Output: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type std::unique_ptr<...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

std::condition_variable – notify once but wait thread wakened twice

Here's a simple C++ thread pool implementation. It's an altered version orginated from #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Web API - Set each thread with the HttpRequestMessage id?

I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

Should checking loop conditions be counted towards total number of comparisons?

I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

Why is the boolean value within a structure within a vector not being updated?

This might sound like a very basic question, but I have trying to fix a simple bug for over an hour now and I can't seem to understand what's happening. I have the following structure declaration in my header file: struct StudentBody { string name; Vec2 position; bool disabled; StudentBody(string...

Crystal convert the idea behind Thread pool to Fibers/spawn

I'm having some hard time learning the idea behind Fibers\coroutines and the implementation in Crystal. I hope this is the right place to ask this, I'll totally accept a "not here" answer :) This is my usual way of handling multi-threading in Ruby: threads = [] max_threads = 10 loop...

How does the kernel separate threads from processes

Suppose I have a browser process like Firefox, that has pid = 123. Firefox has 5 opened tabs each running in a separate thread, so in total it has 5 threads. So I want to know in depth, how the kernel will separate the process into the thread to execute...

Calling variadic template function with no args failing

Given the following code: #include <iostream> template <typename... Args> void foo(Args&&... bargs, Args&&... aargs) { std::cout << "Hello" << std::endl; } int main() { foo<int, double>(1, 2.0, 3, 4.0); //OK foo<char>('c', 'd'); // OK foo(); //FAIL } I get the following compiler error: In function 'int main()': 15:9: error: no...