Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare volatile variables in Swift

Tags:

swift

I want to convert to Swift from Objective-C code like following;

int sum = 0;
x = 1;
for (int i = 0; i < 100; i++) {
    sum += x;
}

x is accessible from other threads. So x is declared as a volatile variable.

volatile int x;

How should I write this code in Swift?

Edited

Sorry for my bad pseudo code.

Just I wanted to read the latest value property or field not from thread cache. Java volatile makes that possible. So does Objective-C volatile. ( does it?)

like image 901
Mitsuaki Ishimoto Avatar asked Jul 26 '14 13:07

Mitsuaki Ishimoto


People also ask

Why do we declare variable as volatile?

volatile is a keyword that must be used when declaring any variable that will reference a device register. If this is not done, the compile-time optimizer might optimize important accesses away. This is important; neglecting to use volatile can result in bugs that are difficult to track down.

Which variables are volatile?

A volatile variable is a variable that is marked or cast with the keyword "volatile" so that it is established that the variable can be changed by some outside factor, such as the operating system or other software.


1 Answers

There is currently no equivalent to volatile in Swift.

In Swift you have access to more potent means of expressing global synchronicity of values than the volatile keyword - which does not provide any kind of atomicity guarantees, and must be used with locks to establish critical sections. For example, you might choose locks to synchronize read and write access to a variable. You might choose to use an MVar to indicate that a variable should only have 1 possible valid state across multiple threads.

Or you might choose to simply not express the problem in Swift. If you're looking for the exact behavior of a volatile variable (which, in your situation, sounds unlikely), stick with C and C++.

like image 189
CodaFi Avatar answered Oct 14 '22 00:10

CodaFi