खोज…


परिचय

समानांतरवाद को विभिन्न वर्गों जैसे std::thread मॉड्यूल, चैनल और एटॉमिक्स के माध्यम से रस्ट के मानक पुस्तकालय द्वारा अच्छी तरह से समर्थित किया गया है। यह अनुभाग इन प्रकारों के उपयोग के माध्यम से आपका मार्गदर्शन करेगा।

एक नया सूत्र शुरू करना

एक नया सूत्र शुरू करने के लिए:

use std::thread;

fn main() {
    thread::spawn(move || {
        // The main thread will not wait for this thread to finish. That
        // might mean that the next println isn't even executed before the
        // program exits.
        println!("Hello from spawned thread");
    });

    let join_handle = thread::spawn(move || {
        println!("Hello from second spawned thread");
        // To ensure that the program waits for a thread to finish, we must
        // call `join()` on its join handle. It is even possible to send a
        // value to a different thread through the join handle, like the
        // integer 17 in this case:
        17
    });

    println!("Hello from the main thread");
    
    // The above three printlns can be observed in any order.

    // Block until the second spawned thread has finished.
    match join_handle.join() {
        Ok(x) => println!("Second spawned thread returned {}", x),
        Err(_) => println!("Second spawned thread panicked")
    }
}

चैनलों के साथ क्रॉस-थ्रेड संचार

एक धागे से दूसरे में डेटा भेजने के लिए चैनल का उपयोग किया जा सकता है। नीचे एक सरल निर्माता-उपभोक्ता प्रणाली का एक उदाहरण है, जहां मुख्य धागा 0, 1, ..., 9 और मान पैदा करता है और स्पॉन्ड थ्रेड उन्हें प्रिंट करता है:

use std::thread;
use std::sync::mpsc::channel;

fn main() {
    // Create a channel with a sending end (tx) and a receiving end (rx).
    let (tx, rx) = channel();

    // Spawn a new thread, and move the receiving end into the thread.
    let join_handle = thread::spawn(move || {
        // Keep receiving in a loop, until tx is dropped!
        while let Ok(n) = rx.recv() { // Note: `recv()` always blocks
            println!("Received {}", n);
        }
    });

    // Note: using `rx` here would be a compile error, as it has been
    // moved into the spawned thread.

    // Send some values to the spawned thread. `unwrap()` crashes only if the
    // receiving end was dropped before it could be buffered.
    for i in 0..10 {
        tx.send(i).unwrap(); // Note: `send()` never blocks
    }

    // Drop `tx` so that `rx.recv()` returns an `Err(_)`.
    drop(tx);

    // Wait for the spawned thread to finish.
    join_handle.join().unwrap();
}

सत्र प्रकार के साथ क्रॉस-थ्रेड संचार

सत्र प्रकार, संकलक को उस प्रोटोकॉल के बारे में बताने का एक तरीका है जिसका उपयोग आप थ्रेड्स के बीच संवाद करने के लिए करना चाहते हैं - जैसे कि HTTP या FTP में प्रोटोकॉल नहीं, लेकिन थ्रेड्स के बीच सूचना प्रवाह का पैटर्न। यह उपयोगी है क्योंकि संकलक अब गलती से आपके प्रोटोकॉल को तोड़ने से रोक देगा और थ्रेड्स के बीच गतिरोध या लाइवलॉक उत्पन्न कर देगा - कुछ डिबग मुद्दों के सबसे कुख्यात, और हाइजेनबग्स का एक प्रमुख स्रोत। सत्र प्रकार ऊपर वर्णित चैनलों के समान काम करते हैं, लेकिन उपयोग शुरू करने के लिए अधिक भयभीत हो सकते हैं। यहाँ एक सरल दो-सूत्र संचार है:

// Session Types aren't part of the standard library, but are part of this crate.
// You'll need to add session_types to your Cargo.toml file.
extern crate session_types;

// For now, it's easiest to just import everything from the library.
use session_types::*;

// First, we describe what our client thread will do. Note that there's no reason
// you have to use a client/server model - it's just convenient for this example.
// This type says that a client will first send a u32, then quit. `Eps` is
// shorthand for "end communication".
// Session Types use two generic parameters to describe the protocol - the first
// for the current communication, and the second for what will happen next.
type Client = Send<u32, Eps>;
// Now, we define what the server will do: it will receive as u32, then quit.
type Server = Recv<u32, Eps>;

// This function is ordinary code to run the client. Notice that it takes    
// ownership of a channel, just like other forms of interthread communication - 
// but this one about the protocol we just defined.
fn run_client(channel: Chan<(), Client>) {
    let channel = channel.send(42);
    println!("The client just sent the number 42!");
    channel.close();
}

// Now we define some code to run the server. It just accepts a value and prints
// it.
fn run_server(channel: Chan<(), Server>) {
    let (channel, data) = channel.recv();
    println!("The server received some data: {}", data);
    channel.close();
}

fn main() {
    // First, create the channels used for the two threads to talk to each other.
    let (server_channel, client_channel) = session_channel();

    // Start the server on a new thread
    let server_thread = std::thread::spawn(move || {
        run_server(server_channel);
    });

    // Run the client on this thread.
    run_client(client_channel);

    // Wait for the server to finish.
    server_thread.join().unwrap();
}

आपको ध्यान देना चाहिए कि मुख्य विधि ऊपर परिभाषित क्रॉस-थ्रेड संचार के लिए मुख्य विधि के समान है, यदि सर्वर को अपने स्वयं के फ़ंक्शन में ले जाया गया था। यदि आप इसे चलाते हैं, तो आपको आउटपुट मिलेगा:

The client just sent the number 42!
The server received some data: 42

उस क्रम में।

क्लाइंट और सर्वर प्रकारों को परिभाषित करने के सभी झंझट से क्यों गुजरना है? और हम क्लाइंट और सर्वर में चैनल को फिर से परिभाषित क्यों करते हैं? इन सवालों का एक ही जवाब है: संकलक हमें प्रोटोकॉल तोड़ने से रोक देगा! यदि क्लाइंट ने इसे भेजने के बजाय डेटा प्राप्त करने की कोशिश की (जिसके परिणामस्वरूप साधारण कोड में गतिरोध होगा), तो प्रोग्राम संकलित नहीं होगा, क्योंकि क्लाइंट के चैनल ऑब्जेक्ट पर एक recv विधि नहीं है। इसके अलावा, अगर हमने प्रोटोकॉल को इस तरह से परिभाषित करने की कोशिश की, जिससे गतिरोध पैदा हो सकता है (उदाहरण के लिए, यदि क्लाइंट और सर्वर दोनों ने मान प्राप्त करने की कोशिश की है), तो संकलन तब विफल हो जाता है जब हम चैनल बनाते हैं। इसका कारण यह है कि Send और Recv "डुअल टाइप्स" हैं, जिसका अर्थ है कि यदि सर्वर एक करता है, तो क्लाइंट को दूसरे को करना होगा - यदि दोनों Recv करने की कोशिश करते हैं, तो आप मुश्किल में पड़ने वाले हैं। Eps का अपना एक अलग प्रकार है, क्योंकि क्लाइंट और सर्वर दोनों के लिए चैनल बंद करने के लिए सहमत होना ठीक है।

बेशक, जब हम चैनल पर कुछ ऑपरेशन करते हैं, तो हम प्रोटोकॉल में एक नई स्थिति में चले जाते हैं, और हमारे लिए उपलब्ध फ़ंक्शन बदल सकते हैं - इसलिए हमें चैनल बाइंडिंग को फिर से परिभाषित करना होगा। सौभाग्य से, session_types हमारे लिए इसका ख्याल रखता है और हमेशा नया चैनल लौटाता है ( close को छोड़कर, जिस स्थिति में कोई नया चैनल नहीं है)। इसका मतलब यह भी है कि एक चैनल पर सभी विधियाँ चैनल का स्वामित्व भी लेती हैं - इसलिए यदि आप चैनल को फिर से परिभाषित करना भूल जाते हैं, तो संकलक आपको इसके बारे में एक त्रुटि देगा। यदि आप इसे बंद किए बिना किसी चैनल को छोड़ देते हैं, तो यह एक रनटाइम त्रुटि है (दुर्भाग्य से, संकलन समय पर जांचना असंभव है)।

केवल Send और Recv तुलना में कई और प्रकार के संचार हैं - उदाहरण के लिए, Offer चैनल के दूसरे पक्ष को प्रोटोकॉल की दो संभावित शाखाओं के बीच चुनने की क्षमता देता है, और Rec और Var एक साथ काम करते हैं और प्रोटोकॉल में लूप और पुनरावृत्ति की अनुमति देते हैं। । session_types GitHub रिपॉजिटरी में सत्र प्रकार और अन्य प्रकार के कई और उदाहरण उपलब्ध हैं। पुस्तकालय के दस्तावेज यहां देखे जा सकते हैं।

एटॉमिक्स और मेमोरी ऑर्डरिंग

परमाणु प्रकार लॉक-मुक्त डेटा संरचनाओं और अन्य समवर्ती प्रकारों के निर्माण खंड हैं। एक मेमोरी ऑर्डर, मेमोरी बैरियर की ताकत का प्रतिनिधित्व करते हुए, परमाणु प्रकार तक पहुंच / संशोधन करते समय निर्दिष्ट किया जाना चाहिए। जंग 5 मेमोरी ऑर्डरिंग प्रिमिटिव प्रदान करता है: रिलैक्स्ड (सबसे कमज़ोर), एक्वायर (रीड उर्फ लोड्स के लिए), रिलीज़ (उर्फ स्टोर्स लिखने के लिए), एकरेल ("एक्वायर-लोड और रिलीज़-फॉर-स्टोर के बराबर"; दोनों के लिए उपयोगी है। एक ही ऑपरेशन में शामिल हैं जैसे कि तुलना और स्वैप), और सीकस्ट (सबसे मजबूत)। नीचे दिए गए उदाहरण में, हम प्रदर्शित करेंगे कि "रिलैक्स्ड" ऑर्डर "एक्वायर" और "रिलीज़" ऑर्डर से कैसे भिन्न है।

use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Barrier};
use std::thread;

struct UsizePair {
    atom: AtomicUsize,
    norm: UnsafeCell<usize>,
}

// UnsafeCell is not thread-safe. So manually mark our UsizePair to be Sync.
// (Effectively telling the compiler "I'll take care of it!")
unsafe impl Sync for UsizePair {}

static NTHREADS: usize = 8;
static NITERS: usize = 1000000;

fn main() {
    let upair = Arc::new(UsizePair::new(0));

    // Barrier is a counter-like synchronization structure (not to be confused
    // with a memory barrier). It blocks on a `wait` call until a fixed number
    // of `wait` calls are made from various threads (like waiting for all
    // players to get to the starting line before firing the starter pistol).
    let barrier = Arc::new(Barrier::new(NTHREADS + 1));

    let mut children = vec![];

    for _ in 0..NTHREADS {
        let upair = upair.clone();
        let barrier = barrier.clone();
        children.push(thread::spawn(move || {
            barrier.wait();

            let mut v = 0;
            while v < NITERS - 1 {
                // Read both members `atom` and `norm`, and check whether `atom`
                // contains a newer value than `norm`. See `UsizePair` impl for
                // details.
                let (atom, norm) = upair.get();
                if atom > norm {
                    // If `Acquire`-`Release` ordering is used in `get` and
                    // `set`, then this statement will never be reached.
                    println!("Reordered! {} > {}", atom, norm);
                }
                v = atom;
            }
        }));
    }

    barrier.wait();

    for v in 1..NITERS {
        // Update both members `atom` and `norm` to value `v`. See the impl for
        // details.
        upair.set(v);
    }

    for child in children {
        let _ = child.join();
    }
}

impl UsizePair {
    pub fn new(v: usize) -> UsizePair {
        UsizePair {
            atom: AtomicUsize::new(v),
            norm: UnsafeCell::new(v),
        }
    }

    pub fn get(&self) -> (usize, usize) {
        let atom = self.atom.load(Ordering::Relaxed); //Ordering::Acquire

        // If the above load operation is performed with `Acquire` ordering,
        // then all writes before the corresponding `Release` store is
        // guaranteed to be visible below.

        let norm = unsafe { *self.norm.get() };
        (atom, norm)
    }

    pub fn set(&self, v: usize) {
        unsafe { *self.norm.get() = v };

        // If the below store operation is performed with `Release` ordering,
        // then the write to `norm` above is guaranteed to be visible to all
        // threads that "loads `atom` with `Acquire` ordering and sees the same
        // value that was stored below". However, no guarantees are provided as
        // to when other readers will witness the below store, and consequently
        // the above write. On the other hand, there is also no guarantee that
        // these two values will be in sync for readers. Even if another thread
        // sees the same value that was stored below, it may actually see a
        // "later" value in `norm` than what was written above. That is, there
        // is no restriction on visibility into the future.

        self.atom.store(v, Ordering::Relaxed); //Ordering::Release
    }
}

नोट: x86 आर्किटेक्चर में मजबूत मेमोरी मॉडल है। यह पोस्ट इसे विस्तार से बताती है। आर्किटेक्चर की तुलना के लिए विकिपीडिया पृष्ठ पर एक नज़र डालें।

पढ़ो-लिखो ताले

RwLocks अवैध या असंगत डेटा देखने से पाठकों को रोकने के दौरान किसी भी निर्माता को किसी भी संख्या में पाठकों को डेटा प्रदान करने की अनुमति देता है।

निम्न उदाहरण RwLock का उपयोग यह दिखाने के लिए करता है कि कैसे एक एकल उत्पादक धागा समय-समय पर एक मूल्य बढ़ा सकता है जबकि दो उपभोक्ता धागे मूल्य पढ़ रहे हैं।

use std::time::Duration;
use std::thread;
use std::thread::sleep;
use std::sync::{Arc, RwLock };

fn main() {
    // Create an u32 with an inital value of 0
    let initial_value = 0u32;

    // Move the initial value into the read-write lock which is wrapped into an atomic reference
    // counter in order to allow safe sharing.
    let rw_lock = Arc::new(RwLock::new(initial_value));

    // Create a clone for each thread
    let producer_lock = rw_lock.clone();
    let consumer_id_lock = rw_lock.clone();
    let consumer_square_lock = rw_lock.clone();

    let producer_thread = thread::spawn(move || {
        loop {
            // write() blocks this thread until write-exclusive access can be acquired and retuns an 
            // RAII guard upon completion
            if let Ok(mut write_guard) = producer_lock.write() {
                // the returned write_guard implements `Deref` giving us easy access to the target value
                *write_guard += 1;

                println!("Updated value: {}", *write_guard);
            }

            // ^
            // |   when the RAII guard goes out of the scope, write access will be dropped, allowing
            // +~  other threads access the lock

            sleep(Duration::from_millis(1000));
        }
    });

    // A reader thread that prints the current value to the screen
    let consumer_id_thread = thread::spawn(move || {
        loop {
            // read() will only block when `producer_thread` is holding a write lock
            if let Ok(read_guard) = consumer_id_lock.read() {
                // the returned read_guard also implements `Deref`
                println!("Read value: {}", *read_guard);
            }

            sleep(Duration::from_millis(500));
        }
    });

    // A second reader thread is printing the squared value to the screen. Note that readers don't
    // block each other so `consumer_square_thread` can run simultaneously with `consumer_id_lock`.
    let consumer_square_thread = thread::spawn(move || {
        loop {
            if let Ok(lock) = consumer_square_lock.read() {
                let value = *lock;
                println!("Read value squared: {}", value * value);
            }

            sleep(Duration::from_millis(750));
        }
    });

    let _ = producer_thread.join();
    let _ = consumer_id_thread.join();
    let _ = consumer_square_thread.join();
}

उदाहरण आउटपुट:

Updated value: 1
Read value: 1
Read value squared: 1
Read value: 1
Read value squared: 1
Updated value: 2
Read value: 2
Read value: 2
Read value squared: 4
Updated value: 3
Read value: 3
Read value squared: 9
Read value: 3
Updated value: 4
Read value: 4
Read value squared: 16
Read value: 4
Read value squared: 16
Updated value: 5
Read value: 5
Read value: 5
Read value squared: 25
...(Interrupted)...


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow