std thread

 STL是指Stand Template Library,标准模板库

#include <iostream>
#include <thread>

void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing...\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}

mutian@mutian:~/soft$ g++  -std=c++0x test.c -lpthread
mutian@mutian:~/soft$ ./a.out
thread 1 executing
Thread 2 executing...
Thread 2 executing...
thread 1 executing
Thread 2 executing...
thread 1 executing
Thread 2 executing...
thread 1 executing
Thread 2 executing...
thread 1 executing
Final value of n is 5

#include <stdio.h>
#include <stdlib.h>
#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for

void thread_task(int n) {
    std::this_thread::sleep_for(std::chrono::seconds(n));
    //std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout << "hello thread "
        << std::this_thread::get_id()
        << " paused " << n << " seconds" << std::endl;
}

int main(int argc, const char *argv[])
{
    std::thread threads[5];
    std::cout << "Spawning 5 threads...\n";
    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }
    std::cout << "Done spawning threads! Now wait for them to join\n";

    int i = 1;
    for (auto& t: threads) {
        std::cout << "i:" << i++ << "joined\n";
        t.join();
    }

    std::cout << "finish.\n";
    return EXIT_SUCCESS;
}

mutian@mutian:~/soft$ g++  -std=c++0x test.c -lpthread
mutian@mutian:~/soft$ ./a.out
Spawning 5 threads...
Done spawning threads! Now wait for them to join
i:1joined
hello thread 140448671471360 paused 1 seconds
i:2joined
hello thread 140448663078656 paused 2 seconds
i:3joined
hello thread 140448654685952 paused 3 seconds
i:4joined
hello thread 140448646293248 paused 4 seconds
i:5joined
hello thread 140448637900544 paused 5 seconds
finish.

 

posted @ 2015-12-16 21:06  牧 天  阅读(182)  评论(0)    收藏  举报