FAQ Database Discussion Community


Threads operating on the one instance of a method

c#,multithreading,mutex
I'm creating an app, where I have 50x50 map. On this map I can add dots, which are new instances of the class "dot". Every dot has it's own thread, and every thread connected with a specific dot operates on the method "explore" of the class, and in this method...

Simple thread/mutex test application is crashing

c++,multithreading,c++11,mutex,mingw-w64
I wrote a simple test program which accumulates random samples to a buffer using multiple threads. Each thread uses a stack for reducing the mutex waits. This is for investigating problems in a much larger program. The code currently crashes on mingw-w64 4.9.2 Any idea why? Debugging halts on "signal-received"...

Rails Instance Variable Conflict between Requests

ruby-on-rails,thread-safety,mutex,puma
I have an array of prices: @price_queue. It is persisted in PostgreSQL as Prices.find(1).price_list and is seeded. When a transaction is initiated, the transaction takes the next price in @price_queue, and gets sent to a payment processor for the charge. def create price_bucket = Prices.find(1) price_bucket.with_lock do @price_queue = price_bucket.price_list...

QMutex in slots

c++,qt,qt5,mutex
Suppose to have the following QT code (QT 5.3.1): void SenderClass::runSignal() { emit mySignal(); } void ReceiverClass::ReceiverClass() { ... connect (senderClassRef, SIGNAL(mySignal()), this, SLOT(mySlot()) ); } void ReceiverClass::mySlot() { //Long operation executions Sleep(1000); qDebug() << "1"; Sleep(1000); qDebug() << "2"; Sleep(1000); qDebug() << "3"; } Calling runSignal() consecutively it happens...

Where should a singleton mutex be released in an IDisposable derived class?

c#,concurrency,mutex,semaphore,idisposable
Background I am working on implementing a derived class of a database accessor that should only allow one thread at a time access to the database. But this question should be applicable to any form of single thread access with the Disposable pattern. In Stephen Cleary's blog he shows how...

Applying two or more mutexes to a section of code

c++,pthreads,mutex,deadlock
I'm studying mutexes and deadlocks in c++ pthreads from http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html I understood them but i stacked at a point. I didn't understand what is the problem of the below code. Can you explain it with simple and clear words please? I quoted from this site: Mutex Deadlock: ... Be careful...

Can't synchronize more than 2 threads with pthread_mutex_lock

c,pthreads,mutex
So I'm doing homework for my C class and I came across a problem. I want to sync the acess to my global array with pthread_mutex_lock() but it seems that when 2 or more threads try to lock at the same time it just bugs. Here's my code: #include <stdio.h>...

Mutex not correctly used? Continuation of past questions

c++,multithreading,mutex
I have a second question that is a continuation of this thread : How Does Windows Pick memory for threads? void ThreadTest(LPTSTR* Pointer, mutex* MutexPtr) { MutexPtr->lock(); wcout << *Pointer << endl; MutexPtr->unlock(); return; } void FakeMain() { mutex Mut; mutex* MutPtr = &Mut; LPTSTR Image = L"First String"; LPTSTR*...

Synchronizing pthreads using mutex in C

c,linux,multithreading,mutex
I've got to write a program that counts series of first 10 terms (sorry for my language, this is the first time that I'm talking about math in english) given by formula (x^i)/i!. So, basically it's trivial. BUT, there's some special requirements. Every single term got to be counted by...

Using same mutex in host app and dll

delphi,mutex
I have a multithreaded application which dynamically loads dlls (plugins). I have threads in DLL. Between host app and dll is my own SDK which purpose is to enable communication with dll plugins (library interface) and to define shared resources between host app and dlls (data structures, etc..). Host app...

Mutex Across Threads?

c#,multithreading,callback,network-programming,mutex
So, I am getting an exception with the code below. I have put the exception details with it, but I believe it is caused by the fact that a different thread releases the lock then the one that starts the lock. I want to do this to potentially allow my...

Applying a mutex into an erlang example

erlang,mutex
I currently have a simple bank account written using erlang, I wish to add a mutex into it so that two deposits cannot be made where the set/get balance can be interupted so that the end value is wrong for example bal A = 10 bal B = 20: WRONG...

Visually where is the Deadlock? Why? How to avoid/fix?

operating-system,mutex,semaphore
I am trying to understand and solve the following problem. The following program attempts to use a pair of semaphores t and s for mutual exclusion. Initially: s = 1, t = 0. Thread 1 Thread 2 -------- -------- 1. P(s); P(s); 2. V(s); V(s); 3. P(t); P(t); 4. V(t);...

How to lock a data structure modified by 2 threads which belong to 2 different classes

c++,multithreading,mutex
Basically, I have a std::map which is shared between 2 classes. Thread1 of class A continuously monitors this map for some info and take action accordingly, and Thread2 of class B updates this map upon receiving some data on some socket. Now how can I prevent this map from corruption,...

luajit/physicsfs mutex deadlock

lua,pthreads,mutex,deadlock,luajit
I've got the following code: local M=ffi.load "physfs" ffi.cdef [[ //basically the preprocessed content of physfs.h, see http://icculus.org/physfs/docs/html/physfs_8h.html ]] M.PHYSFS_init(arg[0]) M.PHYSFS_setSaneConfig("a","b","zip",0,0) function file2str(path) local cpath=ffi.cast("const char *",path) print(1) --debug if M.PHYSFS_exists(cpath)==0 then return nil,"file not found" end print(2) --debug -- some more magic end assert(file2str("someFile.txt")) when calling, I expect debug...

C/C++ arrays with threads - do I need to use mutexes or locks?

c++,c,arrays,multithreading,mutex
I am new to using threads and have read a lot about how data is shared and protecting data. But I have also not really got a good grasp of when I need to use mutexes and locks to protect data. Below is a description of the problem I will...

Can I use WAL mode in SQLite3 if I use an additional mutex for multiple writers?

c++,sqlite3,mutex,wal
http://sqlite.org/wal.html WAL mode is specified for N readers and one writer. It the writer's identity interchangible? For example, I have N writers and an additional mutex. Each writer has to obtain this mutex to be able to write, so there are never two writers writing at the same time. Is...

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

How to add diagnostics to C# lock function for multithreading debugging

c#,multithreading,locking,mutex
Is it possible to shim the C# lock function, to add diagnostics? I would love to see whenever a lock is taken or released, the lock count, and the managed thread id of the thread taking the lock. In C++ you write your own Mutex class and provide your own...

How to correctly serialise thread access to a flag controlling a loop

c++,multithreading,c++11,locking,mutex
I have a function, f1, that contains a simple loop, which is controlled via a boolean flag. The flag is not written to inside f1. I have another function that clears the flag. The two functions are called on different threads. If I lock the mutex before entering the loop...

Mutex assertion error with non-zero heap

c,pthreads,mutex,heap-memory,memset
If I allocate memory, free it and then try to allocate a mutex and lock it, I get the message Assertion 'mutex->__data.__owner == 0'. I am not an expert in concurrency or low-level programming but this seems odd to me. Code #include <stdlib.h> #include <string.h> #include <pthread.h> void nonzero_heap(){ void...

How pthread_mutex_unlock distinguish threads?

c++,c,linux,posix,mutex
Only the owner of mutex can unlock it. But how mutex distinguish thread that locked it? Does threads have any distinctive features in Linux?

What if a condition variable signals to a locked thread?

c,multithreading,pthreads,mutex,condition-variable
In the (pseudo-)code below, cond might wake up while it shouldn't, for whatever reason. So I put a while loop there. When it does wake up, it will still consume the lock, so it is guaranteed that in out() only one thread is doing its job. But what happens if,...

Should I use different mutexes for different objects?

c++,multithreading,mutex
I am new to threading . Correct me if I am wrong that mutex locks the access to a shared data structure so that it cannot be used by other threads until it is unlocked . So, lets consider that there are 2 or more shared data structures . So...

Does Mutex in C# busy wait?

c#,.net,multithreading,mutex
I am wondering if the Mutex object busy waits or does it context switch out (i.e. does the thread owning the mutex go to sleep and get woken up later by an interrupt), or is it architecture dependent (i.e. number of cores your machine has)? I am hoping that it...

Reader doesn't wake up once writer finishes writting in Reader writer lock

c++,multithreading,mutex,deadlock,condition-variable
class ReadLock { private: std::mutex readWriteMutex; std::mutex conditionmtx; std::condition_variable cv; int readings = 0; int writings = 0; int writers = 0; public: void AquireReadLock() { readWriteMutex.lock(); if (writers) { std::unique_lock<std::mutex> lck(conditionmtx); cv.wait(lck); } while (writings) { std::unique_lock<std::mutex> lck(conditionmtx); cv.wait(lck); } readings++; readWriteMutex.unlock(); } void ReleaseReadLock() { readWriteMutex.lock(); //std::unique_lock<std::mutex> lck(conditionmtx);...

How to probe std::mutex?

c++,multithreading,c++11,mutex
I have two threads. Both are talking to GPU. The first one is responsible for rendering the other one for loading stuff. When the first one is actually rendering and not doing other things the second one has to stop. They can run in parallel but that will introduce framerate...

Operating Systems: deadlock possible if a process can only lock one mutex at a time?

system,mutex,deadlock
Is a deadlock possible in an operating system which disallows nested locking, so that a process can only lock one mutex at a time? I think it wouldn't be possible, since for a process to acquire another lock it would need to release any lock it's holding. but I am...

Mutex vs object issue

java,multithreading,mutex
I was looking at java code for Collections.synhronizedMap().I found that it has below implementation.Now my question is 1) why are we using synchronized(mutex) 2) what if we use synchronized(m) I understanding is that if we do synchronized(m) then also only one thread will be able to access the map. static...

How can any thread signal for release of a binary semaphore

multithreading,concurrency,locking,mutex,semaphore
I am new to multithreading paradigm. While learning concurrency, every source I found says: "The difference between mutex and binary semaphore is the ownership i.e. a mutex can be signaled for release by only the thread who created it while a semaphore can be signaled any thread" Considering a scenario...

Code won't advance past wait function for conditional variable

c++,multithreading,mutex,condition-variable
So, I've been trying to get a better understand of how condition variables work and I've written the following code that tries to implement reading and writing from the same text file: #include <iostream> #include <fstream> #include <cstdlib> #include <condition_variable> #include <mutex> #include <thread> using namespace std; mutex mtx; condition_variable...

Is a mutex really necessary in this piece of code?

python,pyqt,mutex
The code below shows a class which I use for PyQt threading functionality. In my main program I instantiate and start this thread (i.e. I use PyQt's moveToThread, and countdown is the run method.). While the thread is running I frequently call the reset method. I'm not sure if the...

Lock mutex in shared memory

c,mutex,mmap
I am trying to use pthread_mutex_t in a mutil Multi-process program, and I need to lock a mutex in a shared memory for synchronization. Here is the code I copy from. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <pthread.h> pthread_mutex_t* g_mutex; void init_mutex(void) { int ret;...

pthread_mutex_errorcheck_np initialization error

c,pthreads,mutex
Below code gives me compilation error: #include<pthread.h> #include<stdio.h> pthread_mutex_t mutex= PTHREAD_MUTEX_ERRORCHECK_NP; int i=0; void *func(void *a) { pthread_mutex_lock(&mutex); i++; printf("The value of thread is: %d\n",i); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main() { pthread_t id1,id2; if(pthread_create(&id1,NULL,func,NULL)<0) perror("pthread_create error\n"); pthread_join(id1,NULL); pthread_join(id2,NULL); } The error is: error: invalid initializer pthread_mutex_t mutex=...

Using Mutex for shared memory of 1 word

c++,c,concurrency,mutex,vxworks
I have an application where multiple threads access and write to a shared memory of 1 word (16bit). Can I expect that the processor reads and writes a word from/to memory in an atomic operation? So I don't need mutex protection of the shared memory/variable? The target is an embedded...

Programmatically close Windows console application c++

c++,windows,mutex,handle
I need my windows console application to be run only in one instance (i.e. Only one instance of the application can be run at a time). Here's what I have: int _tmain(int argc, _TCHAR* argv[]) { PCTSTR Name = TEXT("AnyName"); HANDLE h = CreateMutex(NULL, FALSE, Name); if (GetLastError() == ERROR_ALREADY_EXISTS)...

Use Commands from argv to Initialize a Global Mutex

pthreads,global-variables,global,mutex,argv
What I wish to do is to define a global mutex using data from argv. Not a problem, except that I also want this mutex to be global. This isn't global:: int main (int argc, char **argv) { int arg_1 = atoi(argv[1]); pthread_mutex_t mutex[arg_1]; return 0; } And this isn't...

Unexpected behavior while using condition variable multithread

c,multithreading,mutex,condition-variable
In the code below: #include <stdio.h> #include <pthread.h> pthread_mutex_t mtx; pthread_cond_t cond; int how_many = 10; int pool = 0; void * producer(void * ptr) { while (how_many > 0) { pthread_mutex_lock(&mtx); printf("producer: %d\n", how_many); pool = how_many; how_many--; pthread_mutex_unlock(&mtx); pthread_cond_signal(&cond); } pthread_exit(0); } void * consumer(void * ptr) {...

Why do both the notify and wait function of a std::condition_variable need a locked mutex

c++,multithreading,c++11,locking,mutex
On my neverending quest to understand std::contion_variables I've run into the following. On this page it says the following: void print_id (int id) { std::unique_lock<std::mutex> lck(mtx); while (!ready) cv.wait(lck); // ... std::cout << "thread " << id << '\n'; } And after that it says this: void go() { std::unique_lock<std::mutex>...

Mutex or not to Mutex?

pthreads,mutex
I have an array A of length 1024 and I have 4 threads, the first will work on indexes 0 to 255, the second on 256 to 511, the third on 512 to 767, the last will work on indexes 768 to 1023. Do I need a Mutex for that...

storing mutexes in a vector/deque c++

c++11,mutex
I would like to store a variable number of mutexes in a container like vector or deque. In one of the use cases, I need to reliably and deadlock-free lock all of the mutexes. I would also like to have exception safety guarantee, that if an exception is thrown, all...

Is it possible to check if a Mutex is created by using wildcards?

c#,mutex,wildcard
For example my application creates mutex's like so: MyApplication\\{UserName} and then my updater program (that updates this application) needs to check whether this has been created or not but it doesn't know the username. I have the code: string mutexString = "MyApplication\\User1" bool isNew; var mutex = new Mutex(true, mutexString...

The behavior of method/global variables inside a critical section using Mutex Class

c#,.net,mutex,mutual-exclusion
I am reading a book about C#, I know what a critical section is used for, however this example was on the book and it confuses me: public bool BankTransferWithMutex(int amount) { bool result = false; MyMutex.WaitOne(); if (Balance >= amount) { Balance -= amount; result = true; } MyMutex.ReleaseMutex();...

goroutine blocks when calling RWMutex RLock twice after an RWMutex Unlock

concurrency,go,mutex
var mu sync.RWMutex go func() { mu.RLock() defer mu.RUnlock() mu.RLock() // In my real scenario this second lock happened in a nested function. defer mu.RUnlock() // More code. }() mu.Lock() mu.Unlock() // The goroutine above still hangs. If a function read-locks a read/write mutex twice, while another function write-locks and...

CreateMutex on Windows 2012 with error code ERROR_ACCESS_DENIED

c++,windows,mutex
I am trying to create mutex on Windows 2012 with this code: CreateMutex(securityAttributes, FALSE, TEXT("Global\\test")); it always gives error code 5 (ERROR_ACCESS_DENIED). I have tried to create security attributes that I found here but with no success. Note that this code works on Windows 7. What could be a problem...

Can I create a Windows mutex globally for those processes which know the password of the mutex?

c++,windows,mutex,acl,sid
I want to create a Windows mutex by using WinAPI, CreateMutex() and OpenMutex(). But for security concern, I want the mutex be opened by those processes who know the "password" or the hard-code magic code. I don't want the mutex be accessed by every processes. For example, Create mutex with...

@synchronized - skip instead of wait

objective-c,multithreading,mutex
I've got an Objective-c app with several blocks of code where I only want one thread to be able to access it at a time. Using a @synchronized(self) block works fine for that. However, I've got one block where I want it to skip the block, if another thread is...

Using volatile variables and semaphores - Java

java,multithreading,mutex,semaphore,volatile
I'm starting with Threads, Semaphores, volatile variables, etc. I wonder if when I'm using Semaphores it is necessary to define the variable as volatile, I mean: Having 2 Threads, one increases and the other decreases the variable for example and obviously, before each access I have a mutex that controls...

Necessity of pthread mutex

c,multithreading,pthreads,mutex
I have an int array[100] and I want 5 threads to calculate the sum of all array elements. Each thread iterates through 20 elements within its dedicated range and writes the sum into a global sum variable. Is a mutex necessary here? There is no synchronization needed since all threads...

How should I deal with mutexes in movable types in C++?

c++,mutex,move-constructor
By design, std::mutex is not movable nor copy-constructable. This means that a class A, which holds a mutex, won't receive a default-move-constructor. How would I make this type A movable in a thread-safe way?...