tailieunhanh - Apress Introducing Dot Net 4 With Visual Studio_6

Tham khảo tài liệu 'apress introducing dot net 4 with visual studio_6', công nghệ thông tin, hệ điều hành phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | CHAPTER 12 THREADING IN C private static StreamWriter fsLog new StreamWriter private static void RndThreadFunc using new MySpinLockManager logLock Thread Starting int time 10 200 time using new MySpinLockManager logLock Thread Exiting static void Main Start the threads that wait random time. Thread rndthreads new Thread 50 for uint i 0 i 50 i rndthreads i new Thread new ThreadStart rndthreads i .Start This example is similar to the previous one. It creates 50 threads that wait a random amount of time. However instead of managing a thread count it outputs a line to a log file. This writing is happening from multiple threads and instance methods of StreamWriter are not thread-safe therefore you must do the writing in a safe manner within the context of a lock. That is where the MySpinLock class comes in. Internally it manages a lock variable in the form of an integer and it uses to gate access to the lock. The call to in is saying 1. If the lock value is equal to 0 replace the value with 1 to indicate that the lock is taken otherwise do nothing. 2. If the value of the slot already contains 1 it s taken and you must sleep and spin. Both of those items occur in an atomic fashion via the Interlocked class so there is no possible way that more than one thread at a time can acquire the lock. When the method is called all it needs to do is reset the lock. However that must be done atomically as well hence the call to . 384 CHAPTER 12 THREADING IN C Note Because the internal lock is represented by an int which is an Int32 one could simply set the value to zero in . However as mentioned in the previous sidebar you must be careful if the lock were a 64-bit value and you are running on a .

TỪ KHÓA LIÊN QUAN