Search Results

Search found 112 results on 5 pages for 'semaphore'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Guaranteed semaphore order?

    - by Steve_
    The documentation for the .NET Semaphore class states that: There is no guaranteed order, such as FIFO or LIFO, in which blocked threads enter the semaphore. In this case, if I want a guaranteed order (either FIFO or LIFO), what are my options? Is this something that just isn't easily possible? Would I have to write my own Semaphore? I assume that would be pretty advanced? Thanks, Steve

    Read the article

  • How can I replace this semaphore with a monitor?

    - by Kurru
    Hi In previous question of mine, someone had meantioned that using Semaphores were expensive in C# compared to using a monitor. So I ask this, how can I replace the semaphore in this code with a monitor? I need function1 to return its value after function2 (in a separate thread) has been completed. I had replaced the Semaphore.WaitOne with a Monitor.Wait and the Semaphore.Release with a Monitor.PulseAll but the PulseAll was being triggered before the Wait causing the program to hang. Any idea how to avoid that race condition? Semaphore semaphore = new Semaphore(0,1); byte b; public byte Function1() { // new thread starting in Function2; semaphore.WaitOne(); return b; } public void Function2() { // do some thing b = 0; semaphore.Release(); }

    Read the article

  • Semaphore - What is the use of initial count?

    - by Sandbox
    http://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim.aspx To create a semaphore, I need to provide an initial count and maximum count. MSDN states that an initial count is - The initial number of requests for the semaphore that can be granted concurrently. While it states that maximum count is The maximum number of requests for the semaphore that can be granted concurrently. I can understand that the maximum count is the maximum number of threads that can access a resource concurrently. But, what is the use of initial count? If I create a semaphore with an initial count of 0 and a maximum count of 2, none of my threadpool threads are able to access the resource. If I set the initial count as 1 and maximum count as 2 then only thread pool thread can access the resource. It is only when I set both initial count and maximum count as 2, 2 threads are able to access the resource concurrently. So, I am really confused about the significance of initial count? SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 2); //all threadpool threads wait SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 2);//only one thread has access to the resource at a time SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2, 2);//two threadpool threads can access the resource concurrently

    Read the article

  • Win32 Event vs Semaphore

    - by JP
    Basically I need a replacement for Condition Variable and SleepConditionVariableCS because it only support Vista and UP. (For C++) Some suggested to use Semaphore, I also found CreateEvent. Basically, I need to have on thread waiting on WaitForSingleObject, until something one or more others thread tell me there is something to do. In which context should I use a Semaphore vs an Win Event? Thanks

    Read the article

  • Command line semaphore utility

    - by compie
    I want to write a command line utility that can be used to synchronize the execution off programs in different consoles. Console A: $ first_program && semaphore -signal Console B: $ semaphore -wait && second_program The first program takes a long take to complete. The second program can only start when the first program has finished. Which synchronization object do I need to implement this (in Python)?

    Read the article

  • Command line semaphore utility

    - by compie
    I want to write a command line utility that can be used to synchronize the execution off programs in different consoles. Console A: $ first_program && semaphore -signal Console B: $ semaphore -wait && second_program The first program takes a long take to complete. The second program can only start when the first program has finished. Which synchronization object do I need to implement this?

    Read the article

  • Using boost locks for RAII access to a semaphore

    - by dan
    Suppose I write a C++ semaphore class with an interface that models the boost Lockable concept (i.e. lock(); unlock(); try_lock(); etc.). Is it safe/recommended to use boost locks for RAII access to such an object? In other words, do boost locks (and/or other related parts of the boost thread library) assume that the Lockable concept will only be modeled by mutex-like objects which are locked and unlocked from the same thread? My guess is that it should be OK to use a semaphore as a model for Lockable. I've browsed through some of the boost source and it "seems" OK. The locks don't appear to store explicit references to this_thread or anything like that. Moreover, the Lockable concept doesn't have any function like whichThreadOwnsMe(). It also looks like I should even be able to pass a boost::unique_lock<MySemaphore> reference to boost::condition_variable_any::wait. However, the documentation is not explicitly clear about the requirements. To illustrate what I mean, consider a bare-bones binary semaphore class along these lines: class MySemaphore{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } Now suppose that somewhere, either on an object or globally, I have MySemaphore sem; I want to lock and unlock it using RAII. Also I want to be able to "pass" ownership of the lock from one thread to another. For example, in one thread I execute void doTask() { boost::unique_lock<MySemaphore> lock(sem); doSomeWorkWithSharedObject(); signalToSecondThread(); waitForSignalAck(); lock.release(); } While another thread is executing something like { waitForSignalFromFirstThread(); ackSignal(); boost::unique_lock<MySemaphore>(sem,boost::adopt_lock_t()); doMoreWorkWithSameSharedObject(); } The reason I am doing this is that I don't want anyone else to be able to get the lock on sem in between the time that the first thread executes doSomeWorkWithSharedObject() and the time the second executes doMoreWorkWithSameSharedObject(). Basically, I'm splitting one task into two parts. And the reason I'm splitting the task up is because (1) I want the first part of the task to get started as soon as possible, (2) I want to guarantee that the first part is complete before doTask() returns, and (3) I want the second, more time-consuming part of the task to be completed by another thread, possibly chosen from a pool of slave threads that are waiting around to finish tasks that have been started by master threads. NOTE: I recently posted this same question (sort of) here http://stackoverflow.com/questions/2754884/unlocking-a-mutex-from-a-different-thread-c but I confused mutexes with semaphores, and so the question about using boost locks didn't really get addressed.

    Read the article

  • Semaphore race condition?

    - by poindexter12
    I have created a "Manager" class that contains a limited set of resources. The resources are stored in the "Manager" as a Queue. I initialize the Queue and a Semaphore to the same size, using the semaphore to block a thread if there are no resources available. I have multiple threads calling into this class to request a resource. Here is the psuedo code: public IResource RequestResource() { IResource resource = null; _semaphore.WaitOne(); lock (_syncLock) { resource = _resources.Dequeue(); } return resource; } public void ReleaseResource(IResource resource) { lock (_syncLock) { _resources.Enqueue(resource); } _semaphore.Release(); } While running this application, it seems to run fine for a while. Then, it seems like my Queue is giving out the same object. Does this seem like its possible? I'm pulling my hair out over here, and any help would be greatly appreciated. Feel free to ask for more information if you need it. Thanks!

    Read the article

  • Using a named system semaphore as an event to trigger something in another process.

    - by jbraz
    I have a thread that runs all the time: private void DoSomeStuffThread() { Semaphore sem = new Semaphore(0, 3, "sem_DoStuff"); sem.WaitOne(); do { //do some stuff } while (sem.WaitOne()); } I want to be able to only execute the stuff in the do block when something from another process says so. I am trying to use the "sem_DoStuff" named system semaphore to allow this to happen. The code that gets executed in my other process: public string DoStuff() { try { Semaphore sem = Semaphore.OpenExisting("sem_DoStuff"); sem.Release(); } catch (Exception e) { return e.Message; } } So, the idea is that when DoStuff gets called, the semaphore gets released, and DoSomeStuffThread stops waiting, executes what is in the do block, and then waits for DoStuff again before it is getting called. But, when DoStuff gets called, I'm getting the exception 'No handle of the given name exists.'. What am I doing wrong? Thanks.

    Read the article

  • FIFO semaphore test

    - by L4N0
    Hello everyone, I have implemented FIFO semaphores but now I need a way to test/prove that they are working properly. A simple test would be to create some threads that try to wait on a semaphore and then print a message with a number and if the numbers are in order it should be FIFO, but this is not good enough to prove it because that order could have occurred by chance. Thus, I need a better way of testing it. If necessary locks or condition variables can be used too. Thanks

    Read the article

  • How do I create an inheritable Semaphore in .NET?

    - by pauldoo
    I am trying to create a Win32 Semaphore object which is inheritable. This means that any child processes I launch may automatically have the right to act on the same Win32 object. My code currently looks as follows: Semaphore semaphore = new Semaphore(0, 10); Process process = Process.Start(pathToExecutable, arguments); But the semaphore object in this code cannot be used by the child process. The code I am writing is a port of come working C++. The old C++ code achieves this by the following: SECURITY_ATTRIBUTES security = {0}; security.nLength = sizeof(security); security.bInheritHandle = TRUE; HANDLE semaphore = CreateSemaphore(&security, 0, LONG_MAX, NULL); Then later when CreateProcess is called the bInheritHandles argument is set to TRUE. (In both the C# and C++ case I am using the same child process (which is C++). It takes the semaphore ID on command line, and uses the value directly in a call to ReleaseSemaphore.) I suspect I need to construct a special SemaphoreSecurity or ProcessStartInfo object, but I haven't figured it out yet.

    Read the article

  • The simplest concurrency pattern

    - by Ilya Kogan
    Please, would you help me in reminding me of one of the simplest parallel programming techniques. How do I do the following in C#: Initial state: semaphore counter = 0 Thread 1: // Block until semaphore is signalled semaphore.Wait(); // wait until semaphore counter is 1 Thread 2: // Allow thread 1 to run: semaphore.Signal(); // increments from 0 to 1 It's not a mutex because there is no critical section, or rather you can say there is an infinite critical section. So what is it?

    Read the article

  • Windows Form hangs when running threads

    - by Benjamin Ortuzar
    JI have written a .NET C# Windows Form app in Visual Studio 2008 that uses a Semaphore to run multiple jobs as threads when the Start button is pressed. It’s experiencing an issue where the Form goes into a comma after being run for 40 minutes or more. The log files indicate that the current jobs complete, it picks a new job from the list, and there it hangs. I have noticed that the Windows Form becomes unresponsive when this happens. The form is running in its own thread. This is a sample of the code I am using: protected void ProcessJobsWithStatus (Status status) { int maxJobThreads = Convert.ToInt32(ConfigurationManager.AppSettings["MaxJobThreads"]); Semaphore semaphore = new Semaphore(maxJobThreads, maxJobThreads); // Available=3; Capacity=3 int threadTimeOut = Convert.ToInt32(ConfigurationManager.AppSettings["ThreadSemaphoreWait"]);//in Seconds //gets a list of jobs from a DB Query. List<Job> jobList = jobQueue.GetJobsWithStatus(status); //we need to create a list of threads to check if they all have stopped. List<Thread> threadList = new List<Thread>(); if (jobList.Count > 0) { foreach (Job job in jobList) { logger.DebugFormat("Waiting green light for JobId: [{0}]", job.JobId.ToString()); if (!semaphore.WaitOne(threadTimeOut * 1000)) { logger.ErrorFormat("Semaphore Timeout. A thread did NOT complete in time[{0} seconds]. JobId: [{1}] will start", threadTimeOut, job.JobId.ToString()); } logger.DebugFormat("Acquired green light for JobId: [{0}]", job.JobId.ToString()); // Only N threads can get here at once job.semaphore = semaphore; ThreadStart threadStart = new ThreadStart(job.Process); Thread thread = new Thread(threadStart); thread.Name = job.JobId.ToString(); threadList.Add(thread); thread.Start(); } logger.Info("Waiting for all threads to complete"); //check that all threads have completed. foreach (Thread thread in threadList) { logger.DebugFormat("About to join thread(jobId): {0}", thread.Name); if (!thread.Join(threadTimeOut * 1000)) { logger.ErrorFormat("Thread did NOT complete in time[{0} seconds]. JobId: [{1}]", threadTimeOut, thread.Name); } else { logger.DebugFormat("Thread did complete in time. JobId: [{0}]", thread.Name); } } } logger.InfoFormat("Finished Processing Jobs in Queue with status [{0}]...", status); } //form methods private void button1_Click(object sender, EventArgs e) { buttonStop.Enabled = true; buttonStart.Enabled = false; ThreadStart threadStart = new ThreadStart(DoWork); workerThread = new Thread(threadStart); serviceStarted = true; workerThread.Start(); } private void DoWork() { EmailAlert emailAlert = new EmailAlert (); // start an endless loop; loop will abort only when "serviceStarted" flag = false while (serviceStarted) { emailAlert.ProcessJobsWithStatus(0); // yield if (serviceStarted) { Thread.Sleep(new TimeSpan(0, 0, 1)); } } // time to end the thread Thread.CurrentThread.Abort(); } //job.process() public void Process() { try { //sets the status, DateTimeStarted, and the processId this.UpdateStatus(Status.InProgress); //do something logger.Debug("Updating Status to [Completed]"); //hits, status,DateFinished this.UpdateStatus(Status.Completed); } catch (Exception e) { logger.Error("Exception: " + e.Message); this.UpdateStatus(Status.Error); } finally { logger.Debug("Relasing semaphore"); semaphore.Release(); } I have tried to log what I can into a file to detect where the problem is happening, but so far I haven't been able to identify where this happens. Losing control of the Windows Form makes me think that this has nothing to do with processing the jobs. Any ideas?

    Read the article

  • ubuntu: sem_timedwait not waking (C)

    - by gillez
    I have 3 processes which need to be synchronized. Process one does something then wakes process two and sleeps, which does something then wakes process three and sleeps, which does something and wakes process one and sleeps. The whole loop is timed to run around 25hz (caused by an external sync into process one before it triggers process two in my "real" application). I use sem_post to trigger (wake) each process, and sem_timedwait() to wait for the trigger. This all works successfully for several hours. However at some random time (usually after somewhere between two and four hours), one of the processes starts timing out in sem_timedwait(), even though I am sure the semaphore is being triggered with sem_post(). To prove this I even use sem_getvalue() immediately after the timeout, and the value is 1, so the timedwait should have been triggered. Please see following code: #include <stdio.h> #include <time.h> #include <string.h> #include <errno.h> #include <semaphore.h> sem_t trigger_sem1, trigger_sem2, trigger_sem3; // The main thread process. Called three times with a different num arg - 1, 2 or 3. void *thread(void *arg) { int num = (int) arg; sem_t *wait, *trigger; int val, retval; struct timespec ts; struct timeval tv; switch (num) { case 1: wait = &trigger_sem1; trigger = &trigger_sem2; break; case 2: wait = &trigger_sem2; trigger = &trigger_sem3; break; case 3: wait = &trigger_sem3; trigger = &trigger_sem1; break; } while (1) { // The first thread delays by 40ms to time the whole loop. // This is an external sync in the real app. if (num == 1) usleep(40000); // print sem value before we wait. If this is 1, sem_timedwait() will // return immediately, otherwise it will block until sem_post() is called on this sem. sem_getvalue(wait, &val); printf("sem%d wait sync sem%d. val before %d\n", num, num, val); // get current time and add half a second for timeout. gettimeofday(&tv, NULL); ts.tv_sec = tv.tv_sec; ts.tv_nsec = (tv.tv_usec + 500000); // add half a second if (ts.tv_nsec > 1000000) { ts.tv_sec++; ts.tv_nsec -= 1000000; } ts.tv_nsec *= 1000; /* convert to nanosecs */ retval = sem_timedwait(wait, &ts); if (retval == -1) { // timed out. Print value of sem now. This should be 0, otherwise sem_timedwait // would have woken before timeout (unless the sem_post happened between the // timeout and this call to sem_getvalue). sem_getvalue(wait, &val); printf("!!!!!! sem%d sem_timedwait failed: %s, val now %d\n", num, strerror(errno), val); } else printf("sem%d wakeup.\n", num); // get value of semaphore to trigger. If it's 1, don't post as it has already been // triggered and sem_timedwait on this sem *should* not block. sem_getvalue(trigger, &val); if (val <= 0) { printf("sem%d send sync sem%d. val before %d\n", num, (num == 3 ? 1 : num+1), val); sem_post(trigger); } else printf("!! sem%d not sending sync, val %d\n", num, val); } } int main(int argc, char *argv[]) { pthread_t t1, t2, t3; // create semaphores. val of sem1 is 1 to trigger straight away and start the whole ball rolling. if (sem_init(&trigger_sem1, 0, 1) == -1) perror("Error creating trigger_listman semaphore"); if (sem_init(&trigger_sem2, 0, 0) == -1) perror("Error creating trigger_comms semaphore"); if (sem_init(&trigger_sem3, 0, 0) == -1) perror("Error creating trigger_vws semaphore"); pthread_create(&t1, NULL, thread, (void *) 1); pthread_create(&t2, NULL, thread, (void *) 2); pthread_create(&t3, NULL, thread, (void *) 3); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); } The following output is printed when the program is running correctly (at the start and for a random but long time after). The value of sem1 is always 1 before thread1 waits as it sleeps for 40ms, by which time sem3 has triggered it, so it wakes straight away. The other two threads wait until the semaphore is received from the previous thread. [...] sem1 wait sync sem1. val before 1 sem1 wakeup. sem1 send sync sem2. val before 0 sem2 wakeup. sem2 send sync sem3. val before 0 sem2 wait sync sem2. val before 0 sem3 wakeup. sem3 send sync sem1. val before 0 sem3 wait sync sem3. val before 0 sem1 wait sync sem1. val before 1 sem1 wakeup. sem1 send sync sem2. val before 0 [...] However, after a few hours, one of the threads begins to timeout. I can see from the output that the semaphore is being triggered, and when I print the value after the timeout is is 1. So sem_timedwait should have woken up well before the timeout. I would never expect the value of the semaphore to be 1 after the timeout, save for the very rare occasion (almost certainly never but it's possible) when the trigger happens after the timeout but before I call sem_getvalue. Also, once it begins to fail, every sem_timedwait() on that semaphore also fails in the same way. See the following output, which I've line-numbered: 01 sem3 wait sync sem3. val before 0 02 sem1 wakeup. 03 sem1 send sync sem2. val before 0 04 sem2 wakeup. 05 sem2 send sync sem3. val before 0 06 sem2 wait sync sem2. val before 0 07 sem1 wait sync sem1. val before 0 08 !!!!!! sem3 sem_timedwait failed: Connection timed out, val now 1 09 sem3 send sync sem1. val before 0 10 sem3 wait sync sem3. val before 1 11 sem3 wakeup. 12 !! sem3 not sending sync, val 1 13 sem3 wait sync sem3. val before 0 14 sem1 wakeup. [...] On line 1, thread 3 (which I have confusingly called sem1 in the printf) waits for sem3 to be triggered. On line 5, sem2 calls sem_post for sem3. However, line 8 shows sem3 timing out, but the value of the semaphore is 1. thread3 then triggers sem1 and waits again (10). However, because the value is already 1, it wakes straight away. It doesn't send sem1 again as this has all happened before control is given to thread1, however it then waits again (val is now 0) and sem1 wakes up. This now repeats for ever, sem3 always timing out and showing that the value is 1. So, my question is why does sem3 timeout, even though the semaphore has been triggered and the value is clearly 1? I would never expect to see line 08 in the output. If it times out (because, say thread 2 has crashed or is taking too long), the value should be 0. And why does it work fine for 3 or 4 hours first before getting into this state? This is using Ubuntu 9.4 with kernel 2.6.28. The same procedure has been working properly on Redhat and Fedora. But I'm now trying to port to ubuntu! Thanks for any advice, Giles

    Read the article

  • Using sem_t in a Qt Project

    - by thauburger
    Hi everyone, I'm working on a simulation in Qt (C++), and would like to make use of a Semaphore wrapper class I made for the sem_t type. Although I am including semaphore.h in my wrapper class, running qmake provides the following error: 'sem_t does not name a type' I believe this is a library/linking error, since I can compile the class without problems from the command line. I've read that you can specify external libraries to include during compilation. However, I'm a) not sure how to do this in the project file, and b) not sure which library to include in order to access semaphore.h. Any help would be greatly appreciated. Thanks, Tom Here's the wrapper class for reference: Semaphore.h #ifndef SEMAPHORE_H #define SEMAPHORE_H #include <semaphore.h> class Semaphore { public: Semaphore(int initialValue = 1); int getValue(); void wait(); void post(); private: sem_t mSemaphore; }; #endif Semaphore.cpp #include "Semaphore.h" Semaphore::Semaphore(int initialValue) { sem_init(&mSemaphore, 0, initialValue); } int Semaphore::getValue() { int value; sem_getvalue(&mSemaphore, &value); return value; } void Semaphore::wait() { sem_wait(&mSemaphore); } void Semaphore::post() { sem_post(&mSemaphore); } And, the QT Project File: TARGET = RestaurantSimulation TEMPLATE = app QT += SOURCES += main.cpp \ RestaurantGUI.cpp \ RestaurantSetup.cpp \ WidgetManager.cpp \ RestaurantView.cpp \ Table.cpp \ GUIFood.cpp \ GUIItem.cpp \ GUICustomer.cpp \ GUIWaiter.cpp \ Semaphore.cpp HEADERS += RestaurantGUI.h \ RestaurantSetup.h \ WidgetManager.h \ RestaurantView.h \ Table.h \ GUIFood.h \ GUIItem.h \ GUICustomer.h \ GUIWaiter.h \ Semaphore.h FORMS += RestaurantSetup.ui LIBS += Full Compiler Output: g++ -c -pipe -g -gdwarf-2 -arch i386 -Wall -W -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED - I/usr/local/Qt4.6/mkspecs/macx-g++ -I. - I/Library/Frameworks/QtCore.framework/Versions/4/Headers -I/usr/include/QtCore - I/Library/Frameworks/QtGui.framework/Versions/4/Headers -I/usr/include/QtGui - I/usr/include -I. -I. -F/Library/Frameworks -o main.o main.cpp In file included from RestaurantGUI.h:10, from main.cpp:2: Semaphore.h:14: error: 'sem_t' does not name a type make: *** [main.o] Error 1 make: Leaving directory `/Users/thauburger/Desktop/RestaurantSimulation' Exited with code 2. Error while building project RestaurantSimulation When executing build step 'Make'

    Read the article

  • First toe in the water with Object Databases : DB4O

    - by REA_ANDREW
    I have been wanting to have a play with Object Databases for a while now, and today I have done just that.  One of the obvious choices I had to make was which one to use.  My criteria for choosing one today was simple, I wanted one which I could literally wack in and start using, which means I wanted one which either had a .NET API or was designed/ported to .NET.  My decision was between two being: db4o MongoDb I went for db4o for the single reason that it looked like I could get it running and integrated the quickest.  I am making a Blogging application and front end as a project with which I can test and learn with these object databases.  Another requirement which I thought I would mention is that I also want to be able to use the said database in a shared hosting environment where I cannot install, run and maintain a server instance of said object database.  I can do exactly this with db4o. I have not tried to do this with MongoDb at time of writing.  There are quite a few in the industry now and you read an interesting post about different ones and how they are used with some of the heavy weights in the industry here : http://blog.marcua.net/post/442594842/notes-from-nosql-live-boston-2010 In the example which I am building I am using StructureMap as my IOC.  To inject the object for db4o I went with a Singleton instance scope as I am using a single file and I need this to be available to any thread on in the process as opposed to using the server implementation where I could open and close client connections with the server handling each one respectively.  Again I want to point out that I have chosen to stick with the non server implementation of db4o as I wanted to use this in a shared hosting environment where I cannot have such servers installed and run.     public static class Bootstrapper    {        public static void ConfigureStructureMap()        {            ObjectFactory.Initialize(x => x.AddRegistry(new MyApplicationRegistry()));        }    }    public class MyApplicationRegistry : Registry    {        public const string DB4O_FILENAME = "blog123";        public string DbPath        {            get            {                return Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(IBlogRepository)).Location), DB4O_FILENAME);            }        }        public MyApplicationRegistry()        {            For<IObjectContainer>().Singleton().Use(                () => Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), DbPath));            Scan(assemblyScanner =>            {                assemblyScanner.TheCallingAssembly();                assemblyScanner.WithDefaultConventions();            });        }    } So my code above is the structure map plumbing which I use for the application.  I am doing this simply as a quick scratch pad to play around with different things so I am simply segregating logical layers with folder structure as opposed to different assemblies.  It will be easy if I want to do this with any segment but for the purposes of example I have literally just wacked everything in the one assembly.  You can see an example file structure I have on the right.  I am planning on testing out a few implementations of the object databases out there so I can program to an interface of IBlogRepository One of the things which I was unsure about was how it performed under a multi threaded environment which it will undoubtedly be used 9 times out of 10, and for the reason that I am using the db context as a singleton, I assumed that the library was of course thread safe but I did not know as I have not read any where in the documentation, again this is probably me not reading things correctly.  In short though I threw together a simple test where I simply iterate to a limit each time kicking a common task off with a thread from a thread pool.  This task simply created and added an random Post and added it to the storage. The execution of the threads I put inside the Setup of the Test and then simply ensure the number of posts committed to the database is equal to the number of iterations I made; here is the code I used to do the multi thread jobs: [TestInitialize] public void Setup() { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); var resetEvent = new ManualResetEvent(false); ThreadPool.SetMaxThreads(20, 20); for (var i = 0; i < MAX_ITERATIONS; i++) { ThreadPool.QueueUserWorkItem(delegate(object state) { var eventToReset = (ManualResetEvent)state; var post = new Post { Author = MockUser, Content = "Mock Content", Title = "Title" }; Repository.Put(post); var counter = Interlocked.Decrement(ref _threadCounter); if (counter == 0) eventToReset.Set(); }, resetEvent); } WaitHandle.WaitAll(new[] { resetEvent }); sw.Stop(); Console.WriteLine("{0:00}.{1:00} seconds", sw.Elapsed.Seconds, sw.Elapsed.Milliseconds); }   I was not doing this to test out the speed performance of db4o but while I was doing this I could not help but put in a StopWatch and see out of sheer interest how fast it would take to insert a number of Posts.  I tested it out in this case with 10000 inserts of a small, simple POCO and it resulted in an average of:  899.36 object inserts / second.  Again this is just  simple crude test which came out of my curiosity at how it performed under many threads when using the non server implementation of db4o. The spec summary of the computer I used is as follows: With regards to the actual Repository implementation itself, it really is quite straight forward and I have to say I am very surprised at how easy it was to integrate and get up and running.  One thing I have noticed in the exposure I have had so far is that the Query returns IList<T> as opposed to IQueryable<T> but again I have not looked into this in depth and this could be there already and if not they have provided everything one needs to make there own repository.  An example of a couple of methods from by db4o implementation of the BlogRepository is below: public class BlogRepository : IBlogRepository { private readonly IObjectContainer _db; public BlogRepository(IObjectContainer db) { _db = db; } public void Put(DomainObject obj) { _db.Store(obj); } public void Delete(DomainObject obj) { _db.Delete(obj); } public Post GetByKey(object key) { return _db.Query<Post>(post => post.Key == key).FirstOrDefault(); } … Anyways I hope to get a few more implementations going of the object databases and literally just get familiarized with them and the concept of no sql databases. Cheers for now, Andrew

    Read the article

  • How to fix semaphore timeout period has expired.

    - by Ryan
    I bough a new hard drive and I'm attempting to copy stuff off the old hard drive to the new one. I tried it using Windows Vista and Windows 7 but no go. Then I tried installing some 3rd party updated drivers that were supposed to fix the problem now my Windows Vista disk won't boot. Has anyone had this problem before and how did you fix it?

    Read the article

  • sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)

    - by Robin
    So I am getting the error: "undefined reference to sem_open()" even though I have include the semaphore.h header. The same thing is happening for all my pthread function calls (mutex, pthread_create, etc). Any thoughts? I am using the following command to compile: g++ '/home/robin/Desktop/main.cpp' -o '/home/robin/Desktop/main.out' #include <iostream> using namespace std; #include <pthread.h> #include <semaphore.h> #include <fcntl.h> const char *serverControl = "/serverControl"; sem_t* semID; int main ( int argc, char *argv[] ) { //create semaphore used to control servers semID = sem_open(serverControl,O_CREAT,O_RDWR,0); return 0; }

    Read the article

  • Semaphores in unmanaged code

    - by Dororo
    I've been using the Semaphore class to create semaphores. However, the examples use managed code (requires /clr), and I need to use unmanaged code because it seems FreeType doesn't like working with managed code. How can I create two simple threads which use a semaphore in unmanaged code?

    Read the article

  • Creating semaphores with unmanaged code in C++

    - by Dororo
    I've been using the MSDN Library to create semaphores, located at: http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx However, the examples are using Managed code (requires /clr), and I need to use Unmanaged code because FreeType doesn't like working with Managed code it seems. How would I go about creating 2 simple threads which use a semaphore if I'm using unmanaged code? Many thanks for your help.

    Read the article

  • Java semaphore to syncronize printing to screen

    - by Travis Griswald
    I'm currently stuck on a bit of homework and was wondering if anyone could help - I have to use semaphores in java to syncronize printing letters from 2 threads - one printing "A" and one printing "B". I cannot print out more than 2 of the same character in a row, so output should look like AABABABABABBABABABABAABBAABBABABA At the moment I have 3 semaphores, a binary mutex set to 1, and a counting semaphore, and my thread classes look something like this - public void run() { while (true) { Time.delay(RandomGenerator.integer(0,20)); Semaphores.mutex.down (); System.out.println (produce()); if (printCount > 1) { printCount = 0; Semaphores.mutex.up (); Semaphores.printB.up(); } } } public String produce() { printCount++; return "A"; } public void run() { while (true) { Time.delay(RandomGenerator.integer(0,20)); Semaphores.mutex.down (); System.out.println (produce()); if (printCount > 1) { printCount = 0; Semaphores.mutex.up (); Semaphores.printA.up(); } } } public String produce() { printCount++; return "B"; } Yet whatever I try it either deadlocks, or it seems to be working only printing 2 in a row at most, but always seems to print 3 in a row every now and again! Any help is much appreciated, not looking code or anything just a few pointers if possible :)

    Read the article

  • Locking semaphores in C problem sys/sem

    - by Vojtech R.
    Hi, I have problem with my functions. Sometimes two processes enter into critical section. I can't find problem in this after I spent 10 hours by debugging. On what I should aim? // lock semaphore static int P(int sem_id) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; /* P() */ sem_b.sem_flg = 0; if (semop(sem_id, &sem_b, 1) == -1) { print_error("semop in P", errno); return(0); } return(1); } // unlock semaphore static int V(int sem_id) { struct sembuf sem_b[1]; sem_b.sem_num = 0; sem_b.sem_op = 1; /* V() */ sem_b.sem_flg = 0; if (semop(sem_id, &sem_b, 1) == -1) { print_error("semop in V", errno); return(0); } return(1); } The action loop: int mutex; if ((mutex=semget(key, 1, 0666))>=0) { // semaphore exists } while(1) { P(mutex); assert(get_val(mutex)==0); (*action)++; V(mutex); } Many thanks

    Read the article

  • process semaphores linux - wait

    - by coubeatczech
    Hi, I try to code a simple program that starts and waits on the system semaphore until it gets terminated by signal. union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; int main(){ int semaphores = semget(IPC_PRIVATE,1,IPC_CREAT | 0666); union semun arg; arg.val = 0; semctl(semaphores,0,SETVAL,arg); struct sembuf operations[1]; operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = 0; semop(semaphores,operations,1); fprintf(stderr,"Why?\n"); return 0; } I expect, that everytime this program gets executed, nothing actually happens and it waits on the semaphore, but everytime it goes through the semaphore and writes Why?. Why?

    Read the article

  • Modelling boost::Lockable with semaphore rather than mutex (previously titled: Unlocking a mutex fr

    - by dan
    I'm using the C++ boost::thread library, which in my case means I'm using pthreads. Officially, a mutex must be unlocked from the same thread which locks it, and I want the effect of being able to lock in one thread and then unlock in another. There are many ways to accomplish this. One possibility would be to write a new mutex class which allows this behavior. For example: class inter_thread_mutex{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } I should point out that the above code doesn't guarantee FIFO access, since if one thread calls lock() while another calls unlock(), this first thread may acquire the lock ahead of other threads which are waiting. (Come to think of it, the boost::thread documentation doesn't appear to make any explicit scheduling guarantees for either mutexes or condition variables). But let's just ignore that (and any other bugs) for now. My question is, if I decide to go this route, would I be able to use such a mutex as a model for the boost Lockable concept. For example, would anything go wrong if I use a boost::unique_lock< inter_thread_mutex for RAII-style access, and then pass this lock to boost::condition_variable_any.wait(), etc. On one hand I don't see why not. On the other hand, "I don't see why not" is usually a very bad way of determining whether something will work. The reason I ask is that if it turns out that I have to write wrapper classes for RAII locks and condition variables and whatever else, then I'd rather just find some other way to achieve the same effect. EDIT: The kind of behavior I want is basically as follows. I have an object, and it needs to be locked whenever it is modified. I want to lock the object from one thread, and do some work on it. Then I want to keep the object locked while I tell another worker thread to complete the work. So the first thread can go on and do something else while the worker thread finishes up. When the worker thread gets done, it unlocks the mutex. And I want the transition to be seemless so nobody else can get the mutex lock in between when thread 1 starts the work and thread 2 completes it. Something like inter_thread_mutex seems like it would work, and it would also allow the program to interact with it as if it were an ordinary mutex. So it seems like a clean solution. If there's a better solution, I'd be happy to hear that also. EDIT AGAIN: The reason I need locks to begin with is that there are multiple master threads, and the locks are there to prevent them from accessing shared objects concurrently in invalid ways. So the code already uses loop-level lock-free sequencing of operations at the master thread level. Also, in the original implementation, there were no worker threads, and the mutexes were ordinary kosher mutexes. The inter_thread_thingy came up as an optimization, primarily to improve response time. In many cases, it was sufficient to guarantee that the "first part" of operation A, occurs before the "first part" of operation B. As a dumb example, say I punch object 1 and give it a black eye. Then I tell object 1 to change it's internal structure to reflect all the tissue damage. I don't want to wait around for the tissue damage before I move on to punch object 2. However, I do want the tissue damage to occur as part of the same operation; for example, in the interim, I don't want any other thread to reconfigure the object in such a way that would make tissue damage an invalid operation. (yes, this example is imperfect in many ways, and no I'm not working on a game) So we made the change to a model where ownership of an object can be passed to a worker thread to complete an operation, and it actually works quite nicely; each master thread is able to get a lot more operations done because it doesn't need to wait for them all to complete. And, since the event sequencing at the master thread level is still loop-based, it is easy to write high-level master-thread operations, as they can be based on the assumption that an operation is complete when the corresponding function call returns. Finally, I thought it would be nice to use inter_thread mutex/semaphore thingies using RAII with boost locks to encapsulate the necessary synchronization that is required to make the whole thing work.

    Read the article

1 2 3 4 5  | Next Page >