objective-c,automatic-ref-counting,race-condition
It is safe. Accessing weak pointer and Zeroing weak pointer is in between spinlock_lock and spinlock_unlock. Take a look at the runtime source code http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm Accessing weak pointer id objc_loadWeakRetained(id *location) { id result; SideTable *table; spinlock_t *lock; retry: result = *location; if (!result) return nil; table = SideTable::tableForPointer(result); lock...
You have a few options: Rely on ACID implementation of the database (MySQL in your case). Assuming you are using InnoDB engine, you need to choose the right transaction isolation level (SET TRANSACTION syntax) in combination with the right locking reads mechanism (SELECT ... FOR UPDATE and SELECT ... LOCK...
javascript,arrays,firefox,scope,race-condition
It was a combination of a lazy console when evaluating arrays that Bergi mentioned, and the fact that my delete function when called was given a reference to an array, so that the array could be and was changed by some other part of the code.
java,image,rgb,race-condition,compiler-bug
It's a brain fart I'm afraid. Becaue you're doing everything in the same loop, executing the initial four lines (small copies) in later iterations ends up overwriting the pixels that were written by the last four lines (large copy) in earlier iterations. I'm not sure I worded that brilliantly but...
ruby-on-rails,arrays,concurrency,race-condition,pop
Did you try to use ActiveRecord::Locking::Pessimistic. It uses transaction and database lock. It is supported by PostgreSQL and MySQL according to documentation: MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE You can use it in this way: ticket_inventory = TicketInventory.find(1) ticket_inventory.with_lock do ticket_roll = ticket_inventory.ticket_roll @ticket = ticket_roll.pop ticket_inventory.save end Try it, it could...
The problem is with the way you call ln-- multiple instances at the same time. The way ln "forces" symbolic links is that it unlinks (removes) the destination and recreates it again. But you are calling multiple ln instances at the same time which results in a race condition with...
Let's look at example: (defn test-trans [] (let [x (ref 1) t-inc #(dosync (alter x inc)) t-mul #(dosync (alter x (partial * 2))) fns (flatten (repeat 10 [t-mul t-inc]))] (last (pmap (fn [f] (f)) fns)) @x)) Here we have 2 transactional functions - increase x by 1 and multiply x...
java,multithreading,swing,race-condition
Your mistake is quite simple: you are calling (well, you were if it worked) invokeLater after you are trying to wait for the result: synchronized (r) { try { … r.wait(); // <- here you are waiting } catch (InterruptedException e) { … } } SwingUtilities.invokeLater(r); // <- never reached,...
You can use the lower-level os.open and then os.fdopen to copy the file: import os import shutil # Open the file and raise an exception if it exists fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY) # Copy the file and automatically close files at the end with os.fdopen(fd) as...
asp.net,linq,caching,locking,race-condition
This happens because you're working directly with object, locating in cache. Good practise, to avoid those exceptions and other wierd behavior (when you accidentally modify cache object) is working with copy of cache data. And there are several ways of achieving it, like doing clone or some kind of deep...
multithreading,c++11,atomic,race-condition
If you don't initialise alive_ and only set it once the thread starts, the following interleaving of execution is possible: MAIN: s::solution() MAIN: s.thread_(/*your args*/) MAIN: schedule(s.thread_) to run thread: waiting to start MAIN: s::~solution() MAIN: s.alive_ = false thread: alive_ = true MAIN: s.thread_.join() thread: while(alive_) {} ...
java,garbage-collection,race-condition
Can this really happen? Yes. Can Java GC be disabled for a single method call? No. Are there any work-arounds? Yes: you attempt to retrieve the object from the cache (thereby establishing a strong reference if it's still in the cache), and add to the cache if that reference...
There are two viable solutions: Use a mutex so only one process can access the fancy_get_or_create function at the same time. Capture the error thrown by the database and do something instead: ignore that create, update the row instead of creating it, throw an exception, etc. Edit: another solution might...
c++,multithreading,c++11,race-condition
Suppose we are calling ~myclass from the master thread (call it Thread A), you can check whether it is needed to be stopped in the slave thread (call it Thread B): And we have an Atomic<bool> variable named Stop which is accessible from both Threads. In the thread A: ~myclass()...
exception,c++11,race-condition,raii,stdatomic
The Standard says that if multiple threads access a variable and at least one access is a write, then if the variable isn't atomic and the operations aren't ordered, there is a data race, and a program with a data race has undefined behaviour. Knowing these rules, the compiler can...
c,multithreading,race-condition
g_ant++; isn't atomic operation, which can cause undefined behaviour. You should use pthread_mutex_lock(&mutex); and pthread_mutex_unlock(&mutex); the reason why it 90% times starts at 2 is because thread time enters the function, increments g_ant and sleeps itself. OS tends to take it away from CPU and put there another thread...
So without using a 3rd-party library such as filelock you'll have to do something like this: import os from subprocess import check_call if os.path.exists("/var/run/foo.ock"): print("Backing off...") raise SystemExit(1) try: with open("/var/run/foo.lock", "w"): check_call("/path/to/binary") finally: os.remove("/var/run/foo.lock") The better approach is to use filelock (if you can install 3rd party libraries): from...
c#,multithreading,race-condition
You could consider using a variant of the code that the lock statement actually generates by using Monitor.TryEnter() instead of Monitor.Enter: if (Monitor.TryEnter(_myLock)) { try { // Your code } finally { Monitor.Exit(_myLock); } } else { // Do something else } Then if the lock has already been obtained...
python,parallel-processing,scipy,race-condition
This appears to be a known bug in scipy: See this and this discussion on github. Some workarounds are suggested in these discussions: 1) Execute a single run of the script -- so that the cache file is filled -- and then execute the other runs in parallel. The parallel...
python,io,race-condition,python-import,python-os
The way to do this is to take an exclusive lock each time you open it. The writer holds the lock while writing data, while the reader blocks until the writer releases the lock with the fdclose call. This will of course fail if the file has been partially written...
javascript,google-chrome,google-chrome-extension,race-condition
Track the loading status of the content by adding chrome.webRequest.onBeforeRequest.addListener( function(details) { tabStatus[details.tabId] = 'loading'; }, { urls: ['*://*/*.pdf'], types: ['main_frame'] } ); and tabStatus[details.tabId] = 'complete'; at the end of chrome.webRequest.onCompleted.addListener Conditionally defer the response in the onMessage listener: chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.getInfo) { if...
java,multithreading,race-condition,synchronized
You're right that the race condition exists. But the racy operations are so quick that they're unlikely to happen -- and the synchronized keywords are likely providing synchronization "help" that, while not required by the JLS, hide the races. If you want to make it a bit more obvious, you...
javascript,arrays,race-condition
The drop variable stores the number of cards you are supposed to be riffling from either the left or right hand. However, there are two instances: if (drop >= top.length) { cards = top; } and if (drop >= bottom.length) { cards = bottom; } where drop can be greater...
vb.net,list,task-parallel-library,race-condition,parallel.foreach
I think I found the answer. It is by changing List(Of T) to ConcurrentBag(Of T) resolved the issue. According to the this link The ConcurrentBag<T> collection, in the System.Collections.Concurrent namespace, provides a multiset that is thread-safe. The collection allows you to add and remove items freely from multiple threads without...
algorithm,process,operating-system,synchronization,race-condition
Bounded Waiting is defined as :- There exists a bound, or limit, on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted. Returning to your problem, it...
postgresql,triggers,transactions,race-condition,unique-constraint
By default, unique constraints in PostgreSQL are checked at the end of each statement. It's easy to test the behavior using psql. Some big, red flags . . . As this procedure is run in a function, then it is one big transaction. It's not one, big transaction because you're...
python,django,multithreading,transactions,race-condition
@Sai is on track... the key is that the lock/mutex won't occur until a write (or delete). As coded, there will always be a time between "discovery" (read) of the pending connection and "claim" (write/lock) of the pending connection, with no way to know that a connection is in the...
If you spawn a process and it dies just before you create your monitor, you will still receive the DOWN message: 1> Pid = spawn(erlang,now,[]). <0.35.0> 2> is_process_alive(Pid). false 3> monitor(process, Pid). #Ref<0.0.0.86> 4> flush(). Shell got {'DOWN',#Ref<0.0.0.86>,process,<0.35.0>,noproc} As this shell session shows, we first spawn an intentionally short-lived process,...
c++,multithreading,c++11,race-condition,memory-model
Language-lawyer answer, [intro.multithread] n3485 21 The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. 4 Two expression evaluations conflict...
javascript,object,asynchronous,properties,race-condition
Due to the single-threaded nature of javascript execution, your check is correct in all cases when the value is assigned in one synchronous block, as the control flow cannot "jump" to your checking logic while the assignment is executing.
linux,file-io,path,posix,race-condition
No replies to this question, and I have spent several days trawling through Linux source code. I believe the answer is "currently you can't unlink a file race free", so I have opened a feature request at https://bugzilla.kernel.org/show_bug.cgi?id=93441 to have Linux extend unlinkat() with the AT_EMPTY_PATH Linux extension flag. If...
java,multithreading,jvm,race-condition
The precise term is a data race, which is a specialization of the general concept of a race condition. The term data race is an official, precisely specified concept, which means that it arises from a formal analysis of the code. The only way to get the real picture is...
multithreading,mongodb,concurrency,distributed,race-condition
What you need is findAndModify ;) It allows to do a GET followed by an UPDATE in a single operation. You can use a processing flag, first false and you change it when doing the findAnModify() db.col.findAndModify({ query: { processed: false }, update: { $inc: { score: 1 }, $set:{processed:...
applescript,clipboard,race-condition
The Standard Additions Dictionary says: set the clipboard to v : Place data on an application’s clipboard. Use inside a ‘tell’ block and activate the application first. (Link to AppleScript Wiki) Try it this way: on writeFromClipboard(someText) tell application "TextEdit" activate set oldClipboard to the clipboard set the clipboard to someText...
c++,c++11,singleton,compiler-optimization,race-condition
Ok seeing your comments I'm posting an answer because something needs to be clear : std containers are not "threadsafe". They provide some protection and garantees, like the fact that you can have multiple readers safely. However you cannot have multiple writers, or writers and readers concurrently. Regarding your question...
c,debugging,gdb,printf,race-condition
Is this any better then putting a printf in my code? No, it's much worse. Every breakpoint that is hit in GDB triggers the following chain of events: context switch from running thread to GDB GDB stops all other threads (assuming default all-stop mode) GDB evaluates breakpoint commands GDB...
c#,sql-server,race-condition,azure-webjobssdk,azure-storage-queues
Here is a possible approach that is similar to what the WebJobs SDK does internally to prevent more that one webjob function to process the same blob trigger simultaneously. When a function picks up a message from a queue, create a blob with the same name as the ID in...
The problem is that p1 is shared, and may change during the main body of the loop. Let's say that you have two threads and p1 starts at zero, and that they start at the same time. First rank 0 reaches the critical section and increments p1 to 1 while...
Yes it will fail with a duplicate key value violates unique constraint error. What I do is to place the insertion code in a try/except block and when the exception is thrown I catch it and retry. That simple. Unless the application has a huge amount of users it will...
transactions,redis,race-condition
Since Redis is single threaded, there is no such thing as them happening at the "same time", one will always arrive ahead of the other, though the timing is often beyond your control. Now if you have two processes can be coordinated in some way you can have one defer...
angularjs,race-condition,angularjs-ng-init
It looks like you're using jquery to get the cookie. Why not just use the angular $cookie service which gives you access to cookies right from within your controller. That would eliminate needing to use ng-init at all. In my experience ng-init is only useful when you need to init...
javascript,node.js,asynchronous,race-condition
Short answer: probably not. Longer answer: Node.js is single threaded, so every synchronous block of code is atomic. In particular there are no threads and actually there is no concurrency (everything runs sequentially). Thus there are no race conditions on synchronous blocks of code. Although there are race conditions in...
c++,sockets,race-condition,ioctl
From man ioctl_list: FIONREAD int * That is, FIONREAD expects a pointer to an integer, but you are passing a pointer to a signed char. The solution: change your: signed char w; to int w; or else you will suffer from Undefined Behavior. The explanation of what you are seeing...
c#,unit-testing,mstest,race-condition,staticresource
Almost every time I have run into this issue it boils down to a race condition which is less likely to occur when you are debugging since you are slowing the execution down as you step through the code. I would suggest adding debug or trace statements into the threads...
linux-device-driver,kernel-module,race-condition,device-tree
Its not possible to load same module twice. Loading same module with different Major and Minor number is possible, instead of this you can handle this situation inside your driver.
concurrency,go,race-condition,channel,goroutine
Channel accesses are thread-safe, so you do not need to lock it or make local copies of it or anything like that.
c,linux,posix,race-condition,dup2
There is an explanation in fs/file.c, do_dup2(): /* * We need to detect attempts to do dup2() over allocated but still * not finished descriptor. NB: OpenBSD avoids that at the price of * extra work in their equivalent of fget() - they insert struct * file immediately after grabbing...
c#,concurrency,race-condition,concurrentdictionary
Your ConcurrentDictionary is protected but your list is not. If your list can be accessed from multiple threads (I assume this is the case) you need to use locking around all accesses to the list or you need to use a different construct. After you call TryGetValue in your Remove...
assembly,parallel-processing,fortran,openmp,race-condition
Each thread has its own set of registers. That's obvious in the case when threads execute on separate cores, since each core contains a full set of registers. When multiple threads are time-sharing the same physical core, the state of the user-visible registers is saved when execution switches to a...
c#,backgroundworker,race-condition
According to this it's correct : BackgroundWorker.cs public void RunWorkerAsync(object argument) { if (isRunning) { throw new InvalidOperationException(SR.GetString(SR.BackgroundWorker_WorkerAlreadyRunning)); } isRunning = true; cancellationPending = false; asyncOperation = AsyncOperationManager.CreateOperation(null); threadStart.BeginInvoke(argument, null, null); } ...
c,multithreading,openmp,race-condition
Section 1.4 of the latest OpenMP standard specifies what is the result of a race condition (emphasis mine): If multiple threads write without synchronization to the same memory unit, including cases due to atomicity considerations as described above, then a data race occurs. Similarly, if at least one thread reads...
Instead of using loops and setTimeout, use the similar Javascript tool setInterval. This will run a function repeatedly every N milliseconds. You can use a counter variable to keep track of when to add progress bars and when to stop! http://jsfiddle.net/4odd386e/ var text = document.getElementById("text"); var i = 0; function...
bash,process,zookeeper,race-condition,docker-compose
The way I solved my problem was to use shared volumes between containers, where the first process creates a new file on this volume after it has done it's job and the other process runs a loop to check if this file has been created. Once the 2nd process detects...
java,multithreading,concurrency,thread-safety,race-condition
You have ConcurrentModificationException because you have your locking broken and the reader thread reads the same list (by Iterator) the writer writes to at the same time. Your code looks like a try of lock-free coding. If so, you must use CAS operation like this: while (!VolatileTest.lock.compareAndSet(false, true) { }...
javascript,promise,race-condition,q
As someone who usually promotes using promises, my suggestion is: Do not use promises here Promises represent one time events. They are an abstraction over values, one a promise changes its state it can no longer be changed. A promise starts off as pending and changes state once to either...
java,spring,oracle,hibernate,race-condition
I assume what you would like to know is how to handle concurrency, preventing race conditions which can occur where two parts of the application modify and accidentally overwrite the same data. You have mostly two strategies for this: pessimistic locking and optimistic locking: Pessimistic locking here you assume that...
java,race-condition,runtime.exec,su
I have solved it. I did end up having to echo and check for done, but I have done it without a loop, or sleeping in my thread, so it will fire as soon as it can, without hogging the CPU. The concurrent class I was looking for was CountDownLatch...