Search Results

Search found 269 results on 11 pages for 'volatile'.

Page 2/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Total Order between !different! volatile variables?

    - by andreas
    Hi all, Consider the following Java code: volatile boolean v1 = false; volatile boolean v2 = false; //Thread A v1 = true; if (v2) System.out.println("v2 was true"); //Thread B v2 = true; if (v1) System.out.println("v1 was true"); If there was a globally visible total order for volatile accesses then at least one println would always be reached. Is that actually guaranteed by the Java Standard? Or is an execution like this possible: A: v1 = true; B: v2 = true; A: read v2 = false; B: read v1 = false; A: v2 = true becomes visible (after the if) B: v1 = true becomes visible (after the if) I could only find statements about accesses to the same volatile variable in the Standard (but I might be missing something). "A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order)." http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4.4 Thanks!

    Read the article

  • Why is volatile not considered useful in multithreaded C or C++ programming?

    - by Michael E
    As demonstrated in this answer I recently posted, I seem to be confused about the utility (or lack thereof) of volatile in multi-threaded programming contexts. My understanding is this: any time a variable may be changed outside the flow of control of a piece of code accessing it, that variable should be declared to be volatile. Signal handlers, I/O registers, and variables modified by another thread all constitute such situations. So, if you have a global int foo, and foo is read by one thread and set atomically by another thread (probably using an appropriate machine instruction), the reading thread sees this situation in the same way it sees a variable tweaked by a signal handler or modified by an external hardware condition and thus foo should be declared volatile (or, for multithreaded situations, accessed with memory-fenced load, which is probably a better a solution). How and where am I wrong?

    Read the article

  • Is It Safe to Cast Away volatile?

    - by Yan Cheng CHEOK
    Most of the time, I am doing this way. class a { public: ~ a() { i = 100; // OK delete (int *)j; // Compiler happy. But, is it safe? // Error : delete j; } private: volatile int i; volatile int *j; }; int main() { a aa; } However, I saw an article here: https://www.securecoding.cert.org/confluence/display/seccode/EXP32-C.+Do+not+access+a+volatile+object+through+a+non-volatile+reference Casting away volatile allows access to an object through a non-volatile reference. This can result in undefined and perhaps unintended program behavior. So, what will be the workaround for my above code example?

    Read the article

  • Is it safe to spin on a volatile variable in user-mode threads?

    - by yongsun
    I'm not quite sure if it's safe to spin on a volatile variable in user-mode threads, to implement a light-weight spin_lock, I looked at the tbb source code, tbb_machine.h:170, //! Spin WHILE the value of the variable is equal to a given value /** T and U should be comparable types. */ template<typename T, typename U> void spin_wait_while_eq( const volatile T& location, U value ) { atomic_backoff backoff; while( location==value ) backoff.pause(); } And there is no fences in atomic_backoff class as I can see. While from other user-mode spin_lock implementation, most of them use CAS (Compare and Swap).

    Read the article

  • C++ volatile required when spinning on boost::shared_ptr operator bool()?

    - by JaredC
    I have two threads referencing the same boost::shared_ptr: boost::shared_ptr<Widget> shared; On thread is spinning, waiting for the other thread to reset the boost::shared_ptr: while(shared) boost::thread::yield(); And at some point the other thread will call: shared.reset(); My question is whether or not I need to declare the shared pointer as volatile to prevent the compiler from optimizing the call to shared.operator bool() out of the loop and never detecting the change? I know that if I were simply looping on a variable, waiting for it to reach 0 I would need volatile, but I'm not sure if boost::shared_ptr is implemented in such a way that it is not necessary here.

    Read the article

  • how this scaling down for css code is worked?

    - by harris
    this is a code for scaling down for css. i was wondering, how this worked. please someone explain to me part by part. thank you very much. /* ======================================================================== / / Copyright (C) 2000 - 2009 ND-Tech. Co., Ltd. / / All Rights Reserved. / / ======================================================================== / / Project : ScaleDown Created : 31-AUG-2009 / / File : main.c Contact : [email protected] / / ======================================================================== / / You are free to use or modify this code to the following restrictions: / / Acknowledge ND Tech. Co. Ltd. / / Or, put "Parts of code by ND Tech. Co., Ltd." / / Or, leave this header as it is. / / in somewhere in your code. / / ======================================================================== */ include "vm3224k.h" define CE0CTL *(volatile int *)(0x01800008) define CE2CTL *(volatile int *)(0x01800010) define SDCTL *(volatile int *)(0x01800018) define LED *(volatile short *)(0x90080000) // Definitions for async access(change as you wish) define WSU (2<<28) // Write Setup : 0-15 define WST (8<<22) // Write Strobe: 0-63 define WHD (2<<20) // Write Hold : 0-3 define RSU (2<<16) // Read Setup : 0-15 define TA (3<<14) // Turn Around : 0-3 define RST (8<<8) // Read Strobe : 0-63 define RHD (2<<0) // Read Hold : 0-3 define MTYPE (2<<4) /* EDMA Registers */ define PaRAM_OPT 0 // Options define PaRAM_SRC 1 // Source Address define PaRAM_CNT 2 // Frame count, Element count define PaRAM_DST 3 // Destination Address define PaRAM_IDX 4 // Frame index, Element index define PaRAM_RDL 5 // Element count reload, Link address define EDMA_CIPR *(volatile int *)0x01A0FFE4 // EDMA Channel interrupt pending low register define EDMA_CIER *(volatile int *)0x01A0FFE8 // EDMA Channel interrupt enable low register define EDMA_CCER *(volatile int *)0x01A0FFEC // EDMA Channel chain enable register define EDMA_ER *(volatile int *)0x01A0FFF0 // EDMA Event low register define EDMA_EER *(volatile int *)0x01A0FFF4 // EDMA Event enable low register define EDMA_ECR *(volatile int *)0x01A0FFF8 // EDMA Event clear low register define EDMA_ESR *(volatile int *)0x01A0FFFC // EDMA Event set low register define PRI (2<<29) // 1:High priority, 2:Low priority define ESIZE (1<<27) // 0:32bit, 1:16bit, 2:8bit, 3:reserved define DS2 (0<<26) // 1:2-Dimensional define SUM (0<<24) // 0:no update, 1:increment, 2:decrement, 3:by index define DD2 (0<<23) // 1:2-Dimensional define DUM (0<<21) // 0:no update, 1:increment, 2:decrement, 3:by index define TCINT (1<<20) // 0:disable, 1:enable define TCC (8<<16) // 4 bit code define LINK (0<<1) // 0:disable, 1:enable define FS (1<<0) // 0:element, 1:frame define OptionField_0 (PRI|ESIZE|DS2|SUM|DD2|DUM|TCINT|TCC|LINK|FS) define DD2_1 (1<<23) // 1:2-Dimensional define DUM_1 (1<<21) // 0:no update, 1:increment, 2:decrement, 3:by index define TCC_1 (9<<16) // 4 bit code define OptionField_1 (PRI|ESIZE|DS2|SUM|DD2_1|DUM_1|TCINT|TCC_1|LINK|FS) define TCC_2 (10<<16)// 4 bit code define OptionField_2 (PRI|ESIZE|DS2|SUM|DD2|DUM|TCINT|TCC_2|LINK|FS) define DS2_3 (1<<26) // 1:2-Dimensional define SUM_3 (1<<24) // 0:no update, 1:increment, 2:decrement, 3:by index define TCC_3 (11<<16)// 4 bit code define OptionField_3 (PRI|ESIZE|DS2_3|SUM_3|DD2|DUM|TCINT|TCC_3|LINK|FS) pragma DATA_SECTION ( lcd,".sdram" ) pragma DATA_SECTION ( cam,".sdram" ) pragma DATA_SECTION ( rgb,".sdram" ) pragma DATA_SECTION ( u,".sdram" ) extern cregister volatile unsigned int IER; extern cregister volatile unsigned int CSR; short camcode = 0x08000; short lcdcode = 0x00000; short lcd[2][240][320]; short cam[2][240][320]; short rgb[64][32][32]; short bufsel; int *Cevent,*Levent,*CLink,flag=1; unsigned char v[240][160],out_y[120][160]; unsigned char y[240][320],out_u[120][80]; unsigned char u[240][160],out_v[120][80]; void PLL6713() { int i; // CPU Clock Input : 50MHz *(volatile int *)(0x01b7c100) = *(volatile int *)(0x01b7c100) & 0xfffffffe; for(i=0;i<4;i++); *(volatile int *)(0x01b7c100) = *(volatile int *)(0x01b7c100) | 0x08; *(volatile int *)(0x01b7c114) = 0x08001; // 50MHz/2 = 25MHz *(volatile int *)(0x01b7c110) = 0x0c; // 25MHz * 12 = 300MHz *(volatile int *)(0x01b7c118) = 0x08000; // SYSCLK1 = 300MHz/1 = 300MHz *(volatile int *)(0x01b7c11c) = 0x08001; // SYSCLK2 = 300MHz/2 = 150MHz // Peripheral Clock *(volatile int *)(0x01b7c120) = 0x08003; // SYSCLK3 = 300MHz/4 = 75MHz // SDRAM Clock for(i=0;i<4;i++); *(volatile int *)(0x01b7c100) = *(volatile int *)(0x01b7c100) & 0xfffffff7; for(i=0;i<4;i++); *(volatile int *)(0x01b7c100) = *(volatile int *)(0x01b7c100) | 0x01; } unsigned short ybr_565(short y,short u,short v) { int r,g,b; b = y + 1772*(u-128)/1000; if (b<0) b=0; if (b>255) b=255; g = y - (344*(u-128) + 714*(v-128))/1000; if (g<0) g=0; if (g>255) g=255; r = y + 1402*(v-128)/1000; if (r<0) r=0; if (r>255) r=255; return ((r&0x0f8)<<8)|((g&0x0fc)<<3)|((b&0x0f8)>>3); } void yuyv2yuv(char *yuyv,char *y,char *u,char *v) { int i,j,dy,dy1,dy2,s; for (j=s=dy=dy1=dy2=0;j<240;j++) { for (i=0;i<320;i+=2) { u[dy1++] = yuyv[s++]; y[dy++] = yuyv[s++]; v[dy2++] = yuyv[s++]; y[dy++] = yuyv[s++]; } } } interrupt void c_int06(void) { if(EDMA_CIPR&0x800){ EDMA_CIPR = 0xffff; bufsel=(++bufsel&0x01); Cevent[PaRAM_DST] = (int)cam[(bufsel+1)&0x01]; Levent[PaRAM_SRC] = (int)lcd[(bufsel+1)&0x01]; EDMA_ESR = 0x80; flag=1; } } void main() { int i,j,k,y0,y1,v0,u0; bufsel = 0; CSR &= (~0x1); PLL6713(); // Initialize C6713 PLL CE0CTL = 0xffffbf33;// SDRAM Space CE2CTL = (WSU|WST|WHD|RSU|RST|RHD|MTYPE); SDCTL = 0x57115000; vm3224init(); // Initialize vm3224k2 vm3224rate(1); // Set frame rate vm3224bl(15); // Set backlight VM3224CNTL = VM3224CNTL&0xffff | 0x2; // vm3224 interrupt enable for (k=0;k<64;k++) // Create RGB565 lookup table for (i=0;i<32;i++) for (j=0;j<32;j++) rgb[k][i][j] = ybr_565(k<<2,i<<3,j<<3); Cevent = (int *)(0x01a00000 + 24 * 7); Cevent[PaRAM_OPT] = OptionField_0; Cevent[PaRAM_SRC] = (int)&camcode; Cevent[PaRAM_CNT] = 1; Cevent[PaRAM_DST] = (int)&VM3224ADDH; Cevent = (int *)(0x01a00000 + 24 * 8); Cevent[PaRAM_OPT] = OptionField_1; Cevent[PaRAM_SRC] = (int)&VM3224DATA; Cevent[PaRAM_CNT] = (239<<16)|320; Cevent[PaRAM_DST] = (int)cam[bufsel]; Cevent[PaRAM_IDX] = 0; Levent = (int *)(0x01a00000 + 24 * 9); Levent[PaRAM_OPT] = OptionField_2; Levent[PaRAM_SRC] = (int)&lcdcode; Levent[PaRAM_CNT] = 1; Levent[PaRAM_DST] = (int)&VM3224ADDH; Levent = (int *)(0x01a00000 + 24 * 10); Levent[PaRAM_OPT] = OptionField_3; Levent[PaRAM_SRC] = (int)lcd[bufsel]; Levent[PaRAM_CNT] = (239<<16)|320; Levent[PaRAM_DST] = (int)&VM3224DATA; Levent[PaRAM_IDX] = 0; IER = IER | (1<<6)|3; CSR = CSR | 0x1; EDMA_CCER = (1<<8)|(1<<9)|(1<<10); EDMA_CIER = (1<<11); EDMA_CIPR = 0xffff; EDMA_ESR = 0x80; while (1) { if(flag) { // LED = 0; yuyv2yuv((char *)cam[bufsel],(char *)y,(char *)u,(char *)v); for(j=0;j<240;j++) for(i=0;i<320;i++) lcd[bufsel][j][i]=0; for(j=0;j<240;j+=2) for(i=0;i<320;i+=2) out_y[j>>1][i>>1]=(y[j][i]+y[j][i+1]+y[j+1][i]+y[j+1][i+1])>>2; for(j=0;j<240;j+=2) for(i=0;i<160;i+=2) { out_u[j>>1][i>>1]=(u[j][i]+u[j][i+1]+u[j+1][i]+u[j+1][i+1])>>2; out_v[j>>1][i>>1]=(v[j][i]+v[j][i+1]+v[j+1][i]+v[j+1][i+1])>>2; } for (j=0;j<120;j++) for (i=0;i<160;i+=2) { y0 = out_y[j][i]>>2; u0 = out_u[j][i>>1]>>3; v0 = out_v[j][i>>1]>>3; y1 = out_y[j][i+1]>>2; lcd[bufsel][j+60][i+80]=rgb[y0][u0][v0]; lcd[bufsel][j+60][i+81]=rgb[y1][u0][v0]; } flag=0; // LED = 1; } } }

    Read the article

  • Why doesn't gcc remove this check of a non-volatile variable?

    - by Thomas
    This question is mostly academic. I ask out of curiosity, not because this poses an actual problem for me. Consider the following incorrect C program. #include <signal.h> #include <stdio.h> static int running = 1; void handler(int u) { running = 0; } int main() { signal(SIGTERM, handler); while (running) ; printf("Bye!\n"); return 0; } This program is incorrect because the handler interrupts the program flow, so running can be modified at any time and should therefore be declared volatile. But let's say the programmer forgot that. gcc 4.3.3, with the -O3 flag, compiles the loop body (after one initial check of the running flag) down to the infinite loop .L7: jmp .L7 which was to be expected. Now we put something trivial inside the while loop, like: while (running) putchar('.'); And suddenly, gcc does not optimize the loop condition anymore! The loop body's assembly now looks like this (again at -O3): .L7: movq stdout(%rip), %rsi movl $46, %edi call _IO_putc movl running(%rip), %eax testl %eax, %eax jne .L7 We see that running is re-loaded from memory each time through the loop; it is not even cached in a register. Apparently gcc now thinks that the value of running could have changed. So why does gcc suddenly decide that it needs to re-check the value of running in this case?

    Read the article

  • non-volatile virtual memory for C++ containers

    - by arieberman
    Is there a virtual memory management process that would allow a program to use the standard container structures and classes, but retain these structures and their data when the program is not running (or being used), for use by the program at a later time? This should be possible, but can it be done without changing the source code and its (container) declarations? Is there a standard way of doing this?

    Read the article

  • Is there an easier way of creating a registry volatile subkey in .net?

    - by Simon
    So far I have the below which is taken from http://www.danielmoth.com/Blog/volatile-registrykey.aspx public static class RegistryHelper { public static RegistryKey CreateVolatileSubKey(RegistryKey rk, string subkey, RegistryKeyPermissionCheck permissionCheck) { var rk2 = rk.GetType(); const BindingFlags bfStatic = BindingFlags.NonPublic | BindingFlags.Static; const BindingFlags bfInstance = BindingFlags.NonPublic | BindingFlags.Instance; rk2.GetMethod("ValidateKeyName", bfStatic).Invoke(null, new object[] { subkey }); rk2.GetMethod("ValidateKeyMode", bfStatic).Invoke(null, new object[] { permissionCheck }); rk2.GetMethod("EnsureWriteable", bfInstance).Invoke(rk, null); subkey = (string)rk2.GetMethod("FixupName", bfStatic).Invoke(null, new object[] { subkey }); if (!(bool)rk2.GetField("remoteKey", bfInstance).GetValue(rk)) { var key = (RegistryKey)rk2.GetMethod("InternalOpenSubKey", bfInstance, null, new[] { typeof(string), typeof(bool) }, null).Invoke(rk, new object[] { subkey, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree }); if (key != null) { rk2.GetMethod("CheckSubKeyWritePermission", bfInstance).Invoke(rk, new object[] { subkey }); rk2.GetMethod("CheckSubTreePermission", bfInstance).Invoke(rk, new object[] { subkey, permissionCheck }); rk2.GetField("checkMode", bfInstance).SetValue(key, permissionCheck); return key; } } rk2.GetMethod("CheckSubKeyCreatePermission", bfInstance).Invoke(rk, new object[] { subkey }); int lpdwDisposition; IntPtr hkResult; var srh = Type.GetType("Microsoft.Win32.SafeHandles.SafeRegistryHandle"); var temp = rk2.GetField("hkey", bfInstance).GetValue(rk); var rkhkey = (SafeHandleZeroOrMinusOneIsInvalid)temp; var getregistrykeyaccess = (int)rk2.GetMethod("GetRegistryKeyAccess", bfStatic, null, new[] { typeof(bool) }, null).Invoke(null, new object[] { permissionCheck != RegistryKeyPermissionCheck.ReadSubTree }); var errorCode = RegCreateKeyEx(rkhkey, subkey, 0, null, 1, getregistrykeyaccess, IntPtr.Zero, out hkResult, out lpdwDisposition); var keyNameField = rk2.GetField("keyName", bfInstance); var rkkeyName = (string)keyNameField.GetValue(rk); if (errorCode == 0 && hkResult.ToInt32() > 0) { var rkremoteKey = (bool)rk2.GetField("remoteKey", bfInstance).GetValue(rk); var hkResult2 = srh.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(IntPtr), typeof(bool) }, null).Invoke(new object[] { hkResult, true }); var key2 = (RegistryKey)rk2.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { hkResult2.GetType(), typeof(bool), typeof(bool), typeof(bool), typeof(bool) }, null).Invoke(new[] { hkResult2, permissionCheck != RegistryKeyPermissionCheck.ReadSubTree, false, rkremoteKey, false }); rk2.GetMethod("CheckSubTreePermission", bfInstance).Invoke(rk, new object[] { subkey, permissionCheck }); rk2.GetField("checkMode", bfInstance).SetValue(key2, permissionCheck); if (subkey.Length == 0) { keyNameField.SetValue(key2, rkkeyName); } else { keyNameField.SetValue(key2, rkkeyName + @"\" + subkey); } key2.Close(); return rk.OpenSubKey(subkey, true); } if (errorCode != 0) rk2.GetMethod("Win32Error", bfInstance).Invoke(rk, new object[] { errorCode, rkkeyName + @"\" + subkey }); return null; } [DllImport("advapi32.dll", CharSet = CharSet.Auto)] private static extern int RegCreateKeyEx(SafeHandleZeroOrMinusOneIsInvalid hKey, string lpSubKey, int reserved, string lpClass, int dwOptions, int samDesigner, IntPtr lpSecurityAttributes, out IntPtr hkResult, out int lpdwDisposition); } Which works but is fairly ugly. Is there a better way?

    Read the article

  • using volatile keyword

    - by sap
    As i understand, if we declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value. But in the following program both volatile and non-volatile variables are displaying same value. The volatile variable is not updated for the second thread. Can anybody plz explain this why testValue is not changed. class ExampleThread extends Thread { private int testValue1; private volatile int testValue; public ExampleThread(String str){ super(str); } public void run() { if (getName().equals("Thread 1 ")) { testValue = 10; testValue1= 10; System.out.println( "Thread 1 testValue1 : " + testValue1); System.out.println( "Thread 1 testValue : " + testValue); } if (getName().equals("Thread 2 ")) { System.out.println( "Thread 2 testValue1 : " + testValue1); System.out.println( "Thread 2 testValue : " + testValue); } } } public class VolatileExample { public static void main(String args[]) { new ExampleThread("Thread 1 ").start(); new ExampleThread("Thread 2 ").start(); } } output: Thread 1 testValue1 : 10 Thread 1 testValue : 10 Thread 2 testValue1 : 0 Thread 2 testValue : 0

    Read the article

  • pthread_exit and/or pthread_join causing Abort and SegFaults.

    - by MJewkes
    The following code is a simple thread game, that switches between threads causing the timer to decrease. It works fine for 3 threads, causes and Abort(core dumped) for 4 threads, and causes a seg fault for 5 or more threads. Anyone have any idea why this might be happening? #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <errno.h> #include <assert.h> int volatile num_of_threads; int volatile time_per_round; int volatile time_left; int volatile turn_id; int volatile thread_running; int volatile can_check; void * player (void * id_in){ int id= (int)id_in; while(1){ if(can_check){ if (time_left<=0){ break; } can_check=0; if(thread_running){ if(turn_id==id-1){ turn_id=random()%num_of_threads; time_left--; } } can_check=1; } } pthread_exit(NULL); } int main(int argc, char *args[]){ int i; int buffer; pthread_t * threads =(pthread_t *)malloc(num_of_threads*sizeof(pthread_t)); thread_running=0; num_of_threads=atoi(args[1]); can_check=0; time_per_round = atoi(args[2]); time_left=time_per_round; srandom(time(NULL)); //Create Threads for (i=0;i<num_of_threads;i++){ do{ buffer=pthread_create(&threads[i],NULL,player,(void *)(i+1)); }while(buffer == EAGAIN); } can_check=1; time_left=time_per_round; turn_id=random()%num_of_threads; thread_running=1; for (i=0;i<num_of_threads;i++){ assert(!pthread_join(threads[i], NULL)); } return 0; }

    Read the article

  • Is it possible to prevent out-of-order execution by using single volatile

    - by Yan Cheng CHEOK
    By referring article, it is using a pair of volatile to prevent out-of-order execution. I was wondering, is it possible to prevent it using single volatile? void fun_by_thread_1() { this.isNuclearFactory = true; this.factory = new NuclearFactory(); } void fun_by_thread_2() { Factory _factory = this.factory; if (this.isNuclearFactory) { // Do not operate nuclear factory!!! return; } // If out-of-order execution happens, _factory might // be NuclearFactory instance. _factory.operate(); } Factory factory = new FoodFactory(); volatile boolean isNuclearFactory = false; The reason I ask, is because I have a single guard flag (similar to isNuclearFactory flag), to guard against multiple variables (similar to many Factory). I do not wish to mark all the Factory as volatile. Or, shall I fall into the following solution? void fun_by_thread_1() { try { writer.lock(); this.isNuclearFactory = true; this.factory = new NuclearFactory(); } finally { writer.unlock(); } } void fun_by_thread_2() { try { reader.lock(); Factory _factory = this.factory; if (this.isNuclearFactory) { // Do not operate nuclear factory!!! return; } } finally { reader.unlock(); } _factory.operate(); } Factory factory = new FoodFactory(); boolean isNuclearFactory = false; P/S: I know instanceof. Factory is just an example to demonstrate of out-of-order problem.

    Read the article

  • java - question about thread abortion and deadlock - volatile keyword

    - by Tiyoal
    Hello all, I am having some troubles to understand how I have to stop a running thread. I'll try to explain it by example. Assume the following class: public class MyThread extends Thread { protected volatile boolean running = true; public void run() { while (running) { synchronized (someObject) { while (someObject.someCondition() == false && running) { try { someObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // do something useful with someObject } } } public void halt() { running = false; interrupt(); } } Assume the thread is running and the following statement is evaluated to true: while (someObject.someCondition() == false && running) Then, another thread calls MyThread.halt(). Eventhough this function sets 'running' to false (which is a volatile boolean) and interrupts the thread, the following statement is still executed: someObject.wait(); We have a deadlock. The thread will never be halted. Then I came up with this, but I am not sure if it is correct: public class MyThread extends Thread { protected volatile boolean running = true; public void run() { while (running) { synchronized (someObject) { while (someObject.someCondition() == false && running) { try { someObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // do something useful with someObject } } } public void halt() { running = false; synchronized(someObject) { interrupt(); } } } Is this correct? Is this the most common way to do this? This seems like an obvious question, but I fail to come up with a solution. Thanks a lot for your help.

    Read the article

  • RAID 0 Volatile Volume Cache Mode configuration

    - by SnippetSpace
    I discovered that in IRST there is an option to set a cache mode for my 3 ssd raid 0 array. I've read the documentation by Intel and have some questions: Are there any overall benefits/risks from enabling cache mode? As I'm on a laptop, would write back be recommended? I read it increases chance of data loss on power interruption. What is the difference between how windows handles data integrity and the intel driver? Read only mode seems to have the benefit of faster reads, does it have any downsides? Thanks for your help guys!

    Read the article

  • volatile vs. mutable in C++

    - by skydoor
    Hi I have a question about the difference between volatile and mutable. I noticed that both of the two means that it could be changed. What else? Are they the same thing? What's the difference? Where are they applicable? Why the two ideas are proposed? How to use them in different way? Thanks a lot.

    Read the article

  • Should I make my MutexLock volatile?

    - by sje397
    I have some code in a function that goes something like this: void foo() { { // scope the locker MutexLocker locker(&mutex); // do some stuff.. } bar(); } The function call bar() also locks the mutex. I am having an issue whereby the program crashes (for someone else, who has not as yet provided a stack trace or more details) unless the mutex lock inside bar is disabled. Is it possible that some optimization is messing around with the way I have scoped the locker instance, and if so, would making it volatile fix it? Is that a bad idea? Thanks.

    Read the article

  • Does Monitor.Wait ensure that fields are re-read?

    - by Marc Gravell
    It is generally accepted (I believe!) that a lock will force any values from fields to be reloaded (essentially acting as a memory-barrier or fence - my terminology in this area gets a bit loose, I'm afraid), with the consequence that fields that are only ever accessed inside a lock do not themselves need to be volatile. (If I'm wrong already, just say!) A good comment was raised here, questioning whether the same is true if code does a Wait() - i.e. once it has been Pulse()d, will it reload fields from memory, or could they be in a register (etc). Or more simply: does the field need to be volatile to ensure that the current value is obtained when resuming after a Wait()? Looking at reflector, Wait calls down into ObjWait, which is managed internalcall (the same as Enter). The scenario in question was: bool closing; public bool TryDequeue(out T value) { lock (queue) { // arbitrary lock-object (a private readonly ref-type) while (queue.Count == 0) { if (closing) { // <==== (2) access field here value = default(T); return false; } Monitor.Wait(queue); // <==== (1) waits here } ...blah do something with the head of the queue } } Obviously I could just make it volatile, or I could move this out so that I exit and re-enter the Monitor every time it gets pulsed, but I'm intrigued to know if either is necessary.

    Read the article

  • Thread Synchronisation 101

    - by taspeotis
    Previously I've written some very simple multithreaded code, and I've always been aware that at any time there could be a context switch right in the middle of what I'm doing, so I've always guarded access the shared variables through a CCriticalSection class that enters the critical section on construction and leaves it on destruction. I know this is fairly aggressive and I enter and leave critical sections quite frequently and sometimes egregiously (e.g. at the start of a function when I could put the CCriticalSection inside a tighter code block) but my code doesn't crash and it runs fast enough. At work my multithreaded code needs to be a tighter, only locking/synchronising at the lowest level needed. At work I was trying to debug some multithreaded code, and I came across this: EnterCriticalSection(&m_Crit4); m_bSomeVariable = true; LeaveCriticalSection(&m_Crit4); Now, m_bSomeVariable is a Win32 BOOL (not volatile), which as far as I know is defined to be an int, and on x86 reading and writing these values is a single instruction, and since context switches occur on an instruction boundary then there's no need for synchronising this operation with a critical section. I did some more research online to see whether this operation did not need synchronisation, and I came up with two scenarios it did: The CPU implements out of order execution or the second thread is running on a different core and the updated value is not written into RAM for the other core to see; and The int is not 4-byte aligned. I believe number 1 can be solved using the "volatile" keyword. In VS2005 and later the C++ compiler surrounds access to this variable using memory barriers, ensuring that the variable is always completely written/read to the main system memory before using it. Number 2 I cannot verify, I don't know why the byte alignment would make a difference. I don't know the x86 instruction set, but does mov need to be given a 4-byte aligned address? If not do you need to use a combination of instructions? That would introduce the problem. So... QUESTION 1: Does using the "volatile" keyword (implicity using memory barriers and hinting to the compiler not to optimise this code) absolve a programmer from the need to synchronise a 4-byte/8-byte on x86/x64 variable between read/write operations? QUESTION 2: Is there the explicit requirement that the variable be 4-byte/8-byte aligned? I did some more digging into our code and the variables defined in the class: class CExample { private: CRITICAL_SECTION m_Crit1; // Protects variable a CRITICAL_SECTION m_Crit2; // Protects variable b CRITICAL_SECTION m_Crit3; // Protects variable c CRITICAL_SECTION m_Crit4; // Protects variable d // ... }; Now, to me this seems excessive. I thought critical sections synchronised threads between a process, so if you've got one you can enter it and no other thread in that process can execute. There is no need for a critical section for each variable you want to protect, if you're in a critical section then nothing else can interrupt you. I think the only thing that can change the variables from outside a critical section is if the process shares a memory page with another process (can you do that?) and the other process starts to change the values. Mutexes would also help here, named mutexes are shared across processes, or only processes of the same name? QUESTION 3: Is my analysis of critical sections correct, and should this code be rewritten to use mutexes? I have had a look at other synchronisation objects (semaphores and spinlocks), are they better suited here? QUESTION 4: Where are critical sections/mutexes/semaphores/spinlocks best suited? That is, which synchronisation problem should they be applied to. Is there a vast performance penalty for choosing one over the other? And while we're on it, I read that spinlocks should not be used in a single-core multithreaded environment, only a multi-core multithreaded environment. So, QUESTION 5: Is this wrong, or if not, why is it right? Thanks in advance for any responses :)

    Read the article

  • different thread accessing MemoryStream

    - by Wayne
    There's a bit of code which writes data to a MemoryStream object directly into it's data buffer by calling GetBuffer(). It also uses and updates the Position and SetLength() properties appropriately. This code works purposes 99.9999% of the time. Literally. Only every so many 100,000's of iterations it will barf. The specific problem is that the memory.Position property suddenly returns zero instead of the appropriate value. However, code was added that checks for the 0 and throws an exception which include log of the MemoryStream properties like Position and Length in a separate method. Those return the correct value. Further addition shows that when this rare condition occurs, the memory.Position only has zero inside this particular method. Okay. Obviously, this must be a threading issue. But this code is well locked. However, the nature of this software is that it's organized by "tasks" with a scheduler and so any one of several actual O/S thread may run this code at any give time--but never more than one at a time. So it's my guess that ordinarily it so happens that the same thread keeps getting used for this method and then on a rare occasion a different thread get used. Then due to compiler optimizations, the different thread never gets the correct value. It gets a "stale" value. Ordinarily in a situation like this I would apply a "volatile" keyword to the variable in question. But that (those) variables are inside the MemoryStream object. Does anyone have any other idea? Or does this mean we have to implement our own MemoryStream object? (Just like we end up having to do with practically every collection in .NET?) It's a shame to have such an awesome platform as .NET and have virtually the entire system useless as-is for seriously parallelized applications. If I'm wrong or you have other ideas, please advise. Sincerely, Wayne

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >