winapi - Does wglMakeCurrent, drawing, and multithreading cause a race?

If I have two opengl rendering threads, each of which has a pattern of setting its context, doing drawing at a fixed framerate. Will there be a race?I am worried that the following will happen:Thread 1 calls wglMakeCurrentThread 2 calls wglMakeCurrentThread 2 drawsThread 1 drawsIn turn both threads draw on the context of the second thread.Should I be using locks whenever I set a rendering context, and draw to ensure the operation doesn't interfere with other rendering threads?...Read more

multithreading - Unable to enter critical section

Why is it imposible to enter critical section without Sleep(1)?type TMyThread = class(TThread) public procedure Execute; override; end;var T: TMyThread; c: TRTLCriticalSection;implementationprocedure TForm1.FormCreate(Sender: TObject);begin InitializeCriticalSection(c); T := TMyThread.Create(false);end;procedure TMyThread.Execute;begin repeat EnterCriticalSection(c); Sleep(100); LeaveCriticalSection(c); sleep(1); // can't enter from another thread without it until false;end;procedure TForm1.Button1Click(Sender: TObject)...Read more

multithreading - How do I share access to an AtomicBool between threads?

I have this little program - essentially I want one thread to be able to tell the other to stop via a shared boolean in a struct. use std::thread;use std::thread::JoinHandle;use std::time::Duration;use std::sync::atomic::{AtomicBool, Ordering};struct Test { should_stop: AtomicBool, running_thread_handles: Vec<JoinHandle<()>>}impl Test { fn new() -> Test { Test { should_stop: AtomicBool::new(false), running_thread_handles: Vec::new() } } fn stop(&mut self) { self.sh...Read more

multithreading - Does a procedural macro compile in one thread?

I have implemented a procedural macro to generate a method which returns a number:extern crate unique_type_id;#[macro_use]extern crate unique_type_id_derive;#[test]fn sequential_simple() { use unique_type_id::SequentialTypeId; #[derive(SequentialTypeId)] struct Test1; #[derive(SequentialTypeId)] struct Test2; assert_eq!(Test1::id().0, 0u64); assert_eq!(Test2::id().0, 1u64);}I have this implementation but I don't know whether should I place my static ID under a mutex or not:fn inc_id() -> u64 { unsafe { static m...Read more

multithreading - How do I share handlers between threads?

I am writing a multithreaded webserver and basically I need to copy a Vec<Handler> of user-provided handler objects across multiple threads on server startup. I tried several approaches:1) Define Handler as a trait with a fn process(&mut self, Request) -> Response method. Users would implement it for each handler struct. This approach is very common in languages like C++ or python. The problem is that rust doesn't allow me to copy or clone a trait object as it would imply the Sized bound on it which is forbidden on trait objects.2)...Read more

multithreading - Acquiring a RwLock for read and keep it beyond the scope

I have a thread that periodically calls a callback function. Depending on the state, the callback function shall acquire an RwLock of a resource shared with other threads and keep the resource locked even beyond the scope of the callback function. It shall then again depending on the state release the resource again in a later callback cycle.My idea was to put an Option<RwLockReadGuard<T>> into a struct which would be None when the resource is not locked and Some(RwLockReadGuard<T>) when the resource is locked.Unfortunately, I...Read more

multithreading - pthread rwlock lock/unlock from different threads

The docs says that locking from a thread and unlocking from another a rwlock results in undefined behaviour. I have an array and two threads, one allocating it and one deallocating it, this happens in a cycle, and there are also some threads reading/writing in it, but they never overlap so no synchronization is needed there. The problem is the read/write threads still try to use the array in the timeframe between dealloc - alloc. I was thinking of using a read lock for the read/write threads and lock the array for writing in the dealloc thread ...Read more

multithreading - Is there a way to check if a connection has been closed then finish the thread?

With a code similar to that of this example, a connection goes on forever because the infinite loop never stops. I modified it a bit in order to allow reading not to be blocking the thread:use std::net::{TcpListener, TcpStream};use std::io::{BufRead, BufReader};use std::thread;fn main() { let listener = TcpListener::bind("127.0.0.1:4444").unwrap(); println!("Server is running on 127.0.0.1:4444 ..."); for stream in listener.incoming() { let stream = stream.unwrap(); stream .set_nonblocking(true) .expe...Read more

multithreading - Background worker thread and synchronization in Rust

I'm trying to write a simple library that has a background worker thread that processes commands when the library functions are called. The way that I would normally do it in C is have a global semaphore handle that the worker would block on. The functions would give the semaphore after they sent a command, at which point the worker would unblock etc... There are other ways but this is just an example.I have a few questions about how I can achieve something similar with Rust. How do I prevent a thread from closing once the function that created...Read more

multithreading - How to "unlock" an RwLock?

I'm trying to solve the thread-ring problem. In each thread I read the token valueif it is not mine, check if it's the end of the programif it is then finish the threadotherwise, read again and repeatif it is mine (i.e. has my id) then acquire the write lock, increase the value of the token, check if it's the end then tell main thread that I finished it and finish the current thread loopIf it not over, then release the write lock, and start to read againThere is no unlock. Is there any unlock like the one I need in here?It seems that I should r...Read more

multithreading - Buffer in Rust with Mutex and Condvar

I'm trying to implement a buffer with a single consumer and a single producer. I have only used POSIX Semaphores, however, they're not available in Rust and I'm trying to implement a trivial semaphore problem with Rust sync primitives (Mutex, Condvar, Barrier, ...) but I don't want to use channels. My code behaves too irregularly, with some cases going well and other times it just stops at some number and in other cases it just doesn't start counting.Things appear to work better if I wait 1 second in the main thread till I send the Condvar noti...Read more

multithreading - Send can only be implemented for a struct/enum type, not a trait

I have having difficulty implementing Send for a trait. Full code in the playground.I have a Storage trait :pub trait Storage { fn get_value(&self, key: &str) -> Result<Vec<u8>, Error>; fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error>; fn key_exists(&self, key: &str) -> bool; fn delete_key(&mut self, key: &str) -> Result<(), Error>;}It is part of the Consistency struct:pub struct Consistency<'a> { storage: &'a mut Storage,}I hav...Read more

multithreading - One mutable borrow and multiple immutable borrows

I'm trying to write a program that spawns a background thread that continuously inserts data into some collection. At the same time, I want to keep getting input from stdin and check if that input is in the collection the thread is operating on.Here is a boiled down example:use std::collections::HashSet;use std::thread;fn main() { let mut set: HashSet<String> = HashSet::new(); thread::spawn(move || { loop { set.insert("foo".to_string()); } }); loop { let input: String = get_input_from_stdin(); ...Read more

multithreading - Receiver closing and returning a SendError on attempt to send over channel

I'm trying to set up a two-way communication between two threads: the child thread can both send to and receive from the parent, and the parent can both send to and receive from the child. Due to the fact that channels in Rust are unidirectional, I'm using a set of two channels, organized like this (a snippet from my homebrewed threading library):let (tx, rx) = channel();let (tx2, rx2) = channel();(Endpoint { sender: tx2, receiver: rx, }, Endpoint { sender: tx, receiver: rx2, })My code in my setup function looks like this:let Bi...Read more