Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Implicit Threading: OpenMP, GCD, Java, Python, Go, Rust

Implicit Threading คืออะไร?

การย้ายการจัดการเธรดจากนักพัฒนาไปยังคอมไพเลอร์/ไลบรารี เพื่อลดความซับซ้อนและข้อผิดพลาด

OpenMP (C/C++/Fortran)

ใช้ #pragma omp parallel เพื่อระบุโค้ดที่รันขนานได้ คอมไพเลอร์สร้างเธรดตามจำนวนโปรเซสเซอร์

#include <omp.h>
#include <stdio.h>
int main() {
    #pragma omp parallel
    printf("I am a parallel region.\n");
    return 0;
}

Grand Central Dispatch (GCD) - Apple

ใช้ Blocks (^{ ... }) และ Dispatch Queues (Serial/Concurrent) จัดการเธรดอัตโนมัติ

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(q, ^{ printf("Block running in parallel\n"); });

Java Threads

extends Thread หรือ implements Runnable ต้องมีเมธอด run() เริ่มด้วย start()

Python Threads

ใช้ threading.Thread subclass และ override run() หรือ thread.start_new_thread() (เก่า)

Go Goroutines

เพียงแค่เติม go หน้าการเรียกฟังก์ชัน ใช้ Channels สื่อสาร

go func() { /* work */ }()
// main thread reads from channel

Rust Concurrency

ใช้ thread::spawn(|| { ... }) มี Ownership model ป้องกัน data race โดยคอมไพเลอร์

let handle = thread::spawn(move || { a -= 1; println!("a={}", a); });
handle.join().unwrap();