FAQ Database Discussion Community


Understanding Xcode crash message and @synchronized directive

ios,xcode,multithreading,atomic,synchronized
Trying to write some code that uses iCloudKit singleton in addition to a global variables singleton to share variables and processes across multiple method calls, potentially from multiple iPads. And I have two questions in one. Code crashes with this message right now. 2015-06-09 18:31:18.879 iBeacons Demo[277:24157] *** Terminating app...

protect two variables with atomic in a multi-threading environement

c++,atomic,lock-free
//Thread 1 std::uint64_t getAndResetProcessingTimeInMicro() { auto value = m_cumulatedProcessingTimeCount.load(boost::memory_order_acquire); if (value == 0) return 0; auto processingTime = m_cumulatedProcessingTime.load(boost::memory_order_relaxed); resetProcessingTimeInMicro(); return processingTime / value; } //Thread 2 void addProcessingTimeInMicro(std::uint64_t processedTime) { m_cumulatedProcessingTime.fetch_add(processedTime, boost::memory_order_relaxed); //ctxt switch here //-----HERE------...

C++11 equivalent of Windows SRWLock

multithreading,c++11,atomic
I'm trying to implement my own read/write lock using atomic types. I can easily define exclusive locks, but I fail to create locks for shared reader threads, like SRWLock does (see SRWLock). My question is how to implement locks that can be used in exclusive mode (one reader/writer threads at...

C11 stdatomic and calloc

c,atomic,c11
I've got a structure that contains an atomic field: #include <stdatomic.h> struct s { ... atomic_int a; }; This structure is allocated with calloc: struct s *p = calloc(1, sizeof(struct s)); Is it portable to expect p->a to be initialised to 0? There are enough barriers in the code so...

TAS vs TTAS locking

performance,x86,locking,atomic,spinlock
I'm comparing TAS vs TTAS locking. Here are the code: TAS: .globl _tas_lock_acquire _tas_lock_acquire: repeat: lock btsw $0, (%rdi) jc repeat ret .globl _tas_lock_release _tas_lock_release: lock btrw $0, (%rdi) ret TTAS: .globl _ttas_lock_acquire _ttas_lock_acquire: try_lock: lock btsw $0, (%rdi) jc spinwait ret spinwait: btsw $0, (%rdi) jc spinwait jmp try_lock...

Copying addresses of objects containing an atomic member?

c++,c++11,atomic
Lets say I have a struct AtomicElement: struct AtomicElement{ std::atomic<int32_t> a; }; and I have another class, Object, which contains a reference to one of the above AtomicElement objects: struct Object{ AtomicElement& ae; }; Now elsewhere I have a vector of these AtomicElement objects and I would like to update...

C++ atomic on iOS

c++,ios,atomic,compare-and-swap
I have the next isolated test fragment inside an iOS project: /// ... std::atomic_bool ab; ab.store(true); bool expected = false; while (!ab.compare_exchange_weak(expected, true)); assert(0); // ... Provided that ab is not modified by other threads, I expected, that the loop would be infinite, but after executing I found out that...

replacing NA with value in adjacent column in R

r,vector,replace,atomic,na
I want to replace the NA in the IMIAVG column with the value in the IMILEFT or IMIRIGHT column in the same row when necessary (i.e Row 1, 6, 7). I've tried multiple things but nothing seems to work. Does this need a loop? Please note errors keep coming up...

Ensure atomicity when saving a model

python,django,database,concurrency,atomic
I am quite new to Django, and I am not sure how to manage concurrency. I am building an application to reserve equipments. I have a Reservation model with a ManytomanyField of Equipments. When I create a new reservation, I have to ensure that all the equipments are available. The...

Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load

c++,c++11,atomic,stdatomic
Whilst trying to work with std atomic pointer, I ran into the following. Say I do this: std::atomic<std::string*> myString; // <do fancy stuff with the string... also on other threads> //A can I do this? myString.load()->size() //B can I do this? char myFifthChar = *(myString.load()->c_str() + 5); //C can I...

Memory ordering behavior of std::atomic::load

c++,c++11,atomic,atomicity,memory-fences
Am I wrong to assume that the atomic::load should also act as a memory barrier ensuring that all previous non-atomic writes will become visible by other threads? To illustrate: volatile bool arm1 = false; std::atomic_bool arm2 = false; bool triggered = false; Thread1: arm1 = true; //std::std::atomic_thread_fence(std::memory_order_seq_cst); // this would...

Passing an atomic variable to a function

c++,c++11,atomic
I am trying to pass an atomic variable to a function as follow: // function factor receives an atomic variable void factor(std::atomic<int> ThreadsCounter) { ......... } // main starts here int main() { // Atomic variable declaration std::atomic<int> ThreadsCounter(0); // passing atomic variable to the function factor through a thread...

Basic spin-lock mutex implementation ordering

c++,multithreading,atomic
There is a popular spin-lock mutex version which is spreaded across the Internet and which one might encounter in the Anthony Williams book(C++ Concurrency in Action). Here it is: class SpinLock { std::atomic_flag locked; public: SpinLock() : locked{ATOMIC_FLAG_INIT} { } void lock() { while(locked.test_and_set(std::memory_order_acquire)); } void unlock() { locked.clear(std::memory_order_release); }...

C++11 Atomic memory order with non-atomic variables

c++,multithreading,c++11,atomic,memory-barriers
I am unsure about how the memory ordering guarantees of atomic variables in c++11 affect operations to other memory. Let's say I have one thread which periodically calls the write function to update a value, and another thread which calls read to get the current value. Is it guaranteed that...

Atomic operations on memory mapped files

multithreading,go,thread-safety,atomic
I'm using a memory mapped file and I need to use an atomic store on Go. I would use StoreUint64() if I were working on regularly allocated memory. However, I'm not sure how atomic operations work on memory mapped files. Is it safe to use StoreUint64() on memory mapped files?...

Ensure concurrent (money) transactions in Entity Framework?

c#,mysql,entity-framework,transactions,atomic
Assume I have an account_profile table, which has Score field that is similar to an account's money (the database type is BIGINT(20) and the EntityFramework type is long, because I don't need decimal). Now I have the following function: public long ChangeScoreAmount(int userID, long amount) { var profile = this.Entities.account_profile.First(q...

Is there a way of making atomic shared_ptr in libstd++?

c++,multithreading,c++11,gcc,atomic
I need to use atomic shared_ptr in my code - I have single-reader-multiple-writers scenario where a small data structure will be copied and overwritten by multiple threads. After seeing this and this (and my own tests) it seems that free atomic function still aren't working in GCC 4.9.2. I've tried...

How to update 2 objects atomically in a lock-free manner?

java,multithreading,atomic,lock-free,compare-and-swap
I'm working on class that implements hash-code based atomic locking by multiple objects. The main purpose is to unpark a waiter thread as soon as all required locks become available, thus reducing overall waiting time. Its lockAndGet(List objects) returns a single "composite lock" that involves all listed objects. After the...

Compare-and-Swap over POSIX-compliant filesystem objects

algorithm,filesystems,posix,atomic,compare-and-swap
There are several operations which POSIX-compliant operating systems can do atomically with filesystem objects (files and folders). Here is a list of such presumably atomic operations: rename or move file or folder create hardlink create symlink create folder create and open an empty file Is it possible to build Compare-and-Swap...

Using atomic operation in OpenMP for struct (x,y,z) variable

c++,struct,openmp,atomic
I am developing an OpenMP code in C++ (the compiler is g++ 4.8.2). In a part of my code I need to perform an add atomically on a struct data. The strcut is defined as: struct real3 { float x; float y; float z; }; and I defined addition operator...

Should load-acquire see store-release immediately?

c++,multithreading,atomic,atomicity
Suppose we have one simple variable(std::atomic<int> var) and 2 threads T1 and T2 and we have the following code for T1: ... var.store(2, mem_order); ... and for T2 ... var.load(mem_order) ... Also let's assume that T2(load) executes 123ns later in time(later in the modification order in terms of the C++...

C++ 11 std thread sumation with atomic very slow

c++,c++11,visual-studio-2012,atomic,stdthread
I wanted to learn to use C++ 11 std::threads with VS2012 and I wrote a very simple C++ console program with two threads which just increment a counter. I also want to test the performance difference when two threads are used. Test program is given below: #include <iostream> #include <thread>...

pass a structure to gcc built-ins for atomic accesses

c++,multithreading,atomic
I have a two structures just like below: template <class T> struct pointer_t { T *ptr; uintptr_t tag; }; template <class T> struct Node { T data; pointer_t<Node<T> > next; }; and now I want to pass for example pointer_t<Node<T> > newNext to __sync_bool_compare_and_swap() function. According to the prototype of...

Reduction or atomic operator on unknown global array indices

c,cuda,atomic,reduction
I have the following algorithm: __global__ void Update(int N, double* x, double* y, int* z, double* out) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < N) { x[i] += y[i]; if (y[i] >= 0.) out[z[i]] += x[i]; else out[z[i]] -= x[i]; } } Important to note...

Read a non-atomic variable, atomically?

c++,multithreading,performance,x86,atomic
I have a non-atomic 62-bit double which is incremented in one thread regularly. This access does not need to be atomic. However, this variable is occasionally read (not written) by another thread. If I align the variable on a 64-bit boundary the read is atomic. However, is there any way...

Is this lock free design thread safe?

c++,multithreading,shared-ptr,atomic
In different threads I do the following: shared variable: std::shared_ptr<Data> dataPtr; std::atomic<int> version_number; Thread1, the producer receive new data and do dataPtr.reset(newdata); version_number++; Other threads, consumers are doing: int local_version=0; std::shared_ptr<Data> localPtr; while(local_version!=version_number) localPtr=dataPtr; ...operation on my_ptr... localPtr.reset(); local_version=version_number.load(); Here I know that the consumers might skip some version, if...

Atomic load and store functions produce same assembly code as non-atomic load and store

c,gcc,assembly,atomic
Why is the assembly output of store_idx_x86() the same as store_idx() and load_idx_x86() the same as load_idx()? It was my understanding that __atomic_load_n() would flush the core's invalidation queue, and __atomic_store_n() would flush the core's store buffer. Note -- I complied with: gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16) Update:...

how to assure atomicity without AtomicInteger in java?

java,atomic
Assuming Java 6/7/8: Is there any chance of marking some statement atomic without using e.g. AtomicInteger? From my mini research it seems not to be possible generally, however integer/byte/char operations are atomic by itself though (source). Obviously, there is synchronized but at this point I'd like to avoid it. So...

atomic write/read of a file in nodejs

node.js,save,load,atomic
My nodejs application is built around a "project file". Several modules (by "module", I mean a simple javascript file of my project) of this application need to load, modify and save this file often, via streams (fs.createReadStream, fs.createWriteStream), and since those modules are executed independently from each other, with sometimes...

List of Rows from Data Frames as Vector in R

r,list,row,dataframes,atomic
How can I convert rows into vectors in a list across multiple data frames? I've been having the issue that after converting my rows into list form using: pck <- list(NB[1,],NY[1,],AZ[1,],TB[1,]) I get the error Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) : 'x' must be atomic...

Read a variable in another thread

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

C++ atomic list container

c++,list,stl,containers,atomic
Probably this is a stupid question and I get downvoted but I'll ask it anyways. I'm playing around with std::atomic but I think I didn't fully understand the concept. I'm wondering why there are no atomic Containers. So I played a Little bit around. First I tried the following: std::atomic<std::list<int>...

Why isn't atomic double fully implemented

c++,c++11,concurrency,atomic,interlocked
My question is quite simple. Why isn't std::atomic<double> implemented completely? I know it has to do with interlocked variable access. But I really don't see, why this shouldn't be possible on a double. It's specified that any trivially copyable type can be used. And of course double is amongst them....

Do Java Atomics only require atomicity with respect to the VM

java,multithreading,jvm,atomic,native-code
I was looking at the Java source code for the AtomicInteger class (found here) to see which atomic primitives are required to implement a JVM. I noticed they use the undocumented Unsafe API to implement their atomic integer operations and that the only two primitives they use seem to be...

__sync_val_compare_and_swap vs __sync_bool_compare_and_swap

c++,c,gcc,atomic,built-in
I've been thinking about the return values of these two functions. The __sync_bool_compare_and_swap function's return value seems to have obvious benefits, i.e. I can use it to tell whether the swap operation took place. However I can't see a good use of __sync_val_compare_and_swap's return value. Firstly, lets have a function...

thread::join() blocks when it shouldn't

multithreading,c++11,atomic,race-condition
To understand how to use atomics in C++11, I tried to following code snippet: #include <iostream> #include <thread> #include <atomic> using namespace std; struct solution { atomic<bool> alive_; thread thread_; solution() : thread_([this] { alive_ = true; while (alive_); }) { } ~solution() { alive_ = false; thread_.join(); } };...

Get value of atomic counter (increment) with Rails and Postgres

ruby-on-rails,postgresql,rails-activerecord,atomic,sidekiq
I need to atomically increment a model counter and use its new value (processed by a Sidekiq job). At the moment, I use Group.increment_counter :tasks_count, @task.id in my model which atomically increments the counter. But I also need its new value to send a notification, if the counter has e.g....

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic
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...

Why only std::atomic_flag is guaranteed to be lock-free?

multithreading,c++11,atomic
From C++ Concurrency in Action: difference between std::atomic and std::atomic_flag is that std::atomic may not be lock-free; the implementation may have to acquire a mutex internally in order to ensure the atomicity of the operations I wonder why. If atomic_flag is guaranteed to be lock-free, why isn't it guaranteed for...

does array elements need to be volatile? if so, how can I make it?

java,concurrency,visibility,atomic
Suppose I have little code like this: public class Test { final Data[] dataArray; final int maxSize; volatile long nextWriteNo; volatile long nextReadNo; public Test(int maxSize){ this.dataArray = new Data[maxSize]; this.maxSize = maxSize; this.nextWriteNo = 0L; this.nextReadNo = 0L; } public void write(Data data){ synchronized (this) { dataArray[(int)(nextWriteNo & (maxSize...

idiomatic lazy atoms in clojure

clojure,atomic,lazy-sequences
I am playing a bit with atoms in clojure. I have an atom pointing at a lazy-seq. In another bit of code I want to update the value of the atom to the result of doing next on the sequence, but given that both swap! and reset! return the updated...

Is my Double-Checked Locking Pattern implementation right?

c++,multithreading,mutex,atomic,double-checked-locking
An example in Meyers's book Effective Modern C++, Item 16. in a class caching an expensive-to-compute int, you might try to use a pair of std::atomic avriables instead of a mutex: class Widget { public: int magicValue() const { if (cachedValid) { return cachedValue; } else { auto val1 =...

Atomic boolean, test for current value

java,multithreading,atomic,atomicity
I have problems understanding the AtomicBoolean and how could i make best use of its method getAndSet(boolean newValue); Volatile makes all changes directly in memory, so if CPU cannot cache some value, visibility of changes is guaranteed between threads. Synchronized protects from race conditions. Is the following code thread safe...

Atomic increment of counter column using simple update

sql,transactions,sql-update,atomic
I am trying to understand how to safely increment a counter column, that may be incremented simultaneously by many users (It's a Web API for a mobile app). I've read the popular questions in SO for strategies dealing with the issue but I can't seem to figure what's wrong with...

Go atomic and memory order

c++11,go,atomic,lock-free
I am porting a lock free queue from c++11 to go and i came across things such as auto currentRead = writeIndex.load(std::memory_order_relaxed); and in some cases std::memory_order_release and std::memory_order_aqcuire also the equivelent for the above in c11 is something like unsigned long currentRead = atomic_load_explicit(&q->writeIndex,memory_order_relaxed); the meaning of those is...

C - safety when accessing an integer variable: 1 writer, N readers

c++,c,multithreading,thread-safety,atomic
I've a "static 64-bit integer variable" that gets updated by only one thread. All other threads only read from it. Should i protect this variable using atomic operation (ex. "__sync_add_and_fetch") for safety reasons? Or is it OK to read(resp. write) from (resp. to) it directly? I'm still confused because i...

C11 atomic_load/store and volatile qualifier

c,concurrency,atomic
Why does the parameter in the C11 atomic_load/atomic_store functions has the volatile qualifier? As it is well established that volatile is useless for concurrency use cases (e.g. 1, 2). atomic_load( const volatile A* obj ); void atomic_store( volatile A* obj , C desired); ...

C++11 memory model: why can't compiler move statements across load() operations during optimization?

c++,multithreading,c++11,atomic,memory-model
As I understand, for the sequentially consistent and acquire-release memory models if some x.store(some_value) operation from one thread is synchronized with a x.load() operation from the another one, then: Rule 1. All memory operations that happen before the x.store(some_value) operation must appear before the x.load() operation. This point seems clear...