Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Concurrent Programming

Rust Concurrent Programming

Handling concurrency safely and efficiently is one of the purposes of Rust's creation, mainly solving the problem of server high-load capacity.

The concept of concurrent means that different parts of a program execute independently. This is easily confused with the concept of parallel, which emphasizes "executing at the same time".

Concurrency often results in parallelism.

This chapter covers programming concepts and details related to concurrency.

Thread

A thread is a part of a program that runs independently.

The difference between a thread and a process is that a thread is a concept within a program, and a program is usually executed within a process.

In an environment with an operating system, processes are often scheduled alternately for execution, while threads are scheduled by the program within a process.

Since thread concurrency is very likely to result in parallelism, deadlocks and delay errors that may be encountered in parallelism often occur in programs with concurrency mechanisms.

To solve these problems, many other languages (such as Java, C#) use special runtime software to coordinate resources, but this undoubtedly greatly reduces program execution efficiency.

The C/C++ languages also support multithreading at the lowest level of the operating system, and the language itself and its compiler do not have the ability to detect and avoid parallel errors. This puts great pressure on developers, who need to spend a lot of effort avoiding errors.

Rust does not rely on a runtime environment, which is like C/C++.

But Rust itself designs means in the language, including the ownership mechanism, to eliminate the most common errors as much as possible at the compile stage, which other languages do not have.

But this does not mean we can be careless when programming. To date, problems caused by concurrency have not been fully solved in the public domain, and errors may still occur, so be as careful as possible when programming concurrently!

In Rust, new threads are created through the std::thread::spawn function:

Example

use

std

::

thread

;

use

std

::

time

::

Duration

;

fn

spawn_function

(

)

{

   

for

i

in

0

..

5

{

        println

!

(

"spawned thread print {}"

,

i

)

;

        thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

   

}

}

fn

main

(

)

{

    thread

::

spawn

(

spawn_function

)

;

   

for

i

in

0

..

3

{

        println

!

(

"main thread print {}"

,

i

)

;

        thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

   

}

}

Running result:



main thread print 0

spawned thread print 0

main thread print 1

spawned thread print 1

main thread print 2

spawned thread print 2

The order of this result may vary in some cases, but generally it is printed like this.

This program has a child thread whose purpose is to print 5 lines of text, and the main thread prints three lines of text. But obviously, as the main thread ends, the spawn thread also ends, without completing all its printing.

The parameter of the std::thread::spawn function is a function with no parameters, but the above writing is not recommended. We can use closures to pass a function as a parameter:

Example

use

std

::

thread

;

use

std

::

time

::

Duration

;

fn

main

(

)

{

    thread

::

spawn

(

||

{

       

for

i

in

0

..

5

{

            println

!

(

"spawned thread print {}"

,

i

)

;

            thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

       

}

   

}

)

;

   

for

i

in

0

..

3

{

        println

!

(

"main thread print {}"

,

i

)

;

        thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

   

}

}

A closure is an anonymous function that can be stored in a variable or passed as a parameter to other functions. A closure is equivalent to a Lambda expression in Rust, with the following format:



|参数1, 参数2, ...| -> 返回值类型 {

    // 函数体

}

For example:

Example

fn

main

(

)

{

   

let

inc

=

|

num

:

i32

|

->

i32

{

        num

1

   

}

;

    println

!

(

"inc(5) = {}"

,

inc

(

5

)

)

;

}

Running result:

inc(5) = 6

A closure can omit type declarations to use Rust's automatic type inference mechanism:

Example

fn

main

(

)

{

   

let

inc

=

|

num

|

{

        num

1

   

}

;

    println

!

(

"inc(5) = {}"

,

inc

(

5

)

)

;

}

The result is unchanged.

The join method

Example

use

std

::

thread

;

use

std

::

time

::

Duration

;

fn

main

(

)

{

   

let

handle

=

thread

::

spawn

(

||

{

       

for

i

in

0

..

5

{

            println

!

(

"spawned thread print {}"

,

i

)

;

            thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

       

}

   

}

)

;

   

for

i

in

0

..

3

{

        println

!

(

"main thread print {}"

,

i

)

;

        thread

::

sleep

(

Duration

::

from_millis

(

1

)

)

;

   

}

    handle.join

(

)

.unwrap

(

)

;

}

Running result:

main thread print 0 

spawned thread print 0 

spawned thread print 1 

main thread print 1 

spawned thread print 2 

main thread print 2 

spawned thread print 3 

spawned thread print 4

The join method can make the program stop only after the child thread finishes running.

move Forces Ownership Transfer

This is a situation often encountered:

Example

use

std

::

thread

;

fn

main

(

)

{

   

let

s

=

"hello"

;

   

   

let

handle

=

thread

::

spawn

(

||

{

        println

!

(

"{}"

,

s

)

;

   

}

)

;

    handle.join

(

)

.unwrap

(

)

;

}

Trying to use the current function's resources in a child thread is definitely wrong! Because the ownership mechanism forbids this dangerous situation from occurring, it would break the certainty with which the ownership mechanism destroys resources. We can use the closure's move keyword to handle this:

Example

use

std

::

thread

;

fn

main

(

)

{

   

let

s

=

"hello"

;

   

   

let

handle

=

thread

::

spawn

(

move

||

{

        println

!

(

"{}"

,

s

)

;

   

}

)

;

    handle.join

(

)

.unwrap

(

)

;

}

Message delivery

A main tool for implementing message-passing concurrency in Rust is the channel. A channel consists of two parts: a transmitter and a receiver.

std::sync::mpsc contains the methods for message passing:

Example

use

std

::

thread

;

use

std

::

sync

::

mpsc

;

fn

main

(

)

{

   

let

(

tx

,

rx

)

=

mpsc

::

channel

(

)

;

    thread

::

spawn

(

move

||

{

       

let

val

=

String

::

from

(

"hi"

)

;

        tx.send

(

val

)

.unwrap

(

)

;

   

}

)

;

   

let

received

=

rx.recv

(

)

.unwrap

(

)

;

    println

!

(

"Got: {}"

,

received

)

;

}

Running result:



Got: hi

The child thread obtains the main thread's transmitter tx and calls its send method to send a string, which the main thread then receives through the corresponding receiver rx.