C++11 thread(1)

原文地址:http://www.cplusplus.com/reference/thread/thread/thread/

public member function

<thread>

std::thread::thread

default (1)
thread() noexcept;
initialization (2)
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3)
thread (const thread&) = delete;
move (4)
thread (thread&& x) noexcept;

Construct thread

Constructs a thread object:

构造一个线程对象。

(1) default constructor

Construct a thread object that does not represent
any thread of execution.

构造一个不执行任何线程的线程对象。

例子:

#include <iostream>
#include <thread>
using namespace std;
int main()
{
	thread t;
	cout<<"t.id="<<t.get_id()<<endl;

}

运行情况:

可以看到,t是处于non-executing(未执行)状态的。

(2) initialization constructor

Construct a thread object that represents a new joinable thread
of execution.

The new thread of execution calls fn passing args as arguments (using decay copies of
its lvalue or rvalue references).

The completion of this construction synchronizes with the beginning of the invocation of this copy of fn.


构造一个新的可等待的线程对象。


新的线程将调用函数fn并将args传递给fn.


该构造完成与fn的复制完成同步。(即fn复制完该构造就完成了)


例子:

#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void show(int n){
	cout<<"Now n is "<<n<<endl;
}
int main()
{
	int m=10;
	thread t(show,99);
	t.join();//使t能执行完
	cout<<"ok!"<<endl;
}

运行截图:


(3) copy constructor

Deleted constructor form (thread objects cannot
be copied).

默认被Delete的构造器。(线程对象不能被复制)

(4) move constructor
Construct a thread object that acquires the thread of execution represented by x (if
any). This operation does not affect the execution of the moved thread in any way, it simply transfers its handler.

The x object no longer represents any thread of execution.

从执行中的线程x中构造。该操作不会以任何方式影响执行中的线程,只会移交其控制权。

x不再代理任何线程的执行。

例子:

#include <iostream>
#include <thread>
#include <vector>
#include <ctime>
using namespace std;
//delay(n) 延时n秒
void delay(double sec)
{
    time_t start_time, cur_time; // 变量声明
    time(&start_time);
    do {
        time(&cur_time);
        }while((cur_time - start_time) < sec );
};
void show(int n){
	while(n>5){
		cout<<"currentThread is "<<pthread_self()<<",Now n is "<<n<<endl;
		delay(0.5);
		n--;
	}
}
thread returnThread(){

	cout<<"returnThread start!"<<endl;
	thread t(show,10);
	delay(2);
	cout<<"returnThread called!"<<endl;
	return t;
}
int main()
{

	thread t2(returnThread());
	t2.join();
	cout<<"ok!"<<endl;
}

运行截图:

这是我电脑上运行一次的结果,结果不一定一样。

thread objects that are joinable shall
either be joined or detached before
they are destroyed.

可连接线程对象在销毁之前应该被joined或者detached.

Parameters

fn
A pointer to function, pointer to member, or any kind of move-constructible function
object (i.e., an object whose class defines operator(), including closures and function objects).

The return value (if any) is ignored.


fn为一个指向函数的指针,或者一个指向成员的的指针,甚至是任一的可以被移动构造的函数对象。


fn的返回值会被忽略。

args...
Arguments passed to the call to fn (if any). Their types shall be move-constructible.

If fn is a member pointer, the first argument shall be an object for
which that member is defined (or a reference, or a pointer to it).


fn函数的参数。

x

thread object whose state
is moved to the constructed object.

x是一个线程对象。

Fn and Args... are template parameters: if implicitly deduced, these are the proper lvalue or rvalue reference
type to bind the arguments to. Note though, that on the call to fn in the new thread, decay
copies
 of fn and args... are always used (see std::ref for
a wrapper class that makes references copyable).

Fn,Args是模版参数,如果是隐式推导,那么这会绑定相应的左值或者右值,fn将会在新线程中被调用。

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// constructing threads
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

std::atomic<int> global_counter (0);

void increase_global (int n) { for (int i=0; i<n; ++i) ++global_counter; }

void increase_reference (std::atomic<int>& variable, int n) { for (int i=0; i<n; ++i) ++variable; }

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase global counter with 10 threads...\n";
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_global,1000));

  std::cout << "increase counter (foo) with 10 threads using reference...\n";
  std::atomic<int> foo;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(increase_reference,std::ref(foo),1000));

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "global_counter: " << global_counter << ‘\n‘;
  std::cout << "foo: " << foo << ‘\n‘;
  std::cout << "bar: " << bar << ‘\n‘;

  return 0;
}

Edit
& Run

Output:

increase global counter using 10 threads...
increase counter (foo) with 10 threads using reference...
increase counter (bar) with 10 threads using member...
synchronizing all threads...
global_counter: 10000
foo: 10000
bar: 10000

Data races

The move constructor (4) modifies x.

Exception safety

The initialization constructor (2) throws an exception on the following conditions:

exception type error condition description
system_error errc::resource_unavailable_try_again The system is unable to start a new thread

It also throws if the construction of any of the copies it makes (of the decay types of Fn and Args...)
throws.

Depending on the library implementation, this constructor may also throw exceptions to report other situations (such as bad_alloc orsystem_error with
other error conditions).

如果复制过程出错,会抛出system_error错误。

Note that if an exception is thrown from the function invocation (i.e., from fn itself), it is handled by the new thread. If this invocation terminates with an uncaught exception, terminate() is
called.

如果fn抛出异常,线程将会将控制权移交给新的线程,如果不捕获异常,将调用terminate.

——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:[email protected]

2014-9-3

于GDUT

——————————————————————————————————————————————————————————————————

时间: 2024-10-05 04:58:27

C++11 thread(1)的相关文章

再探c++11 Thread库之原子操作

我在之前一篇博文<初探c++11 Thread库之使写多线程程序>中,着重介绍了<thread>头文件中的std::thread类以及其上的一些基本操作,至此我们动手写多线程程序已经基本没有问题了.但是,单线程的那些"坑"我们仍还不知道怎么去避免. 多线程存在的问题 多线程最主要的问题就是共享数据带来的问题.如果共享数据都是只读的,那么没问题,因为只读操作不会影响到数据,更不会涉及对数据的修改,所以所有线程都会获得同样的数据.但是,当一个或多个线程要修改共享数据

初探C++11 Thread

Thread 开启一个线程 使用c++11开启一个线程是比较简单的,如下: #include<iostream> #include<thread> using namespace std; void hello() { cout<<"hello kitty"<<endl; } int main() { std::thread t(hello); t.join(); return 0; } 输出结果: 也可以通过函数对象的方式 #inclu

C++11 thread

1 //这里使用c++的thread创建了5个线程,并支持传递多个参数 2 void thread1(int aa,int bb) 3 { 4 cout << aa << bb << endl; 5 } 6 7 void testthread() 8 { 9 int ithreads[] = {1,2,3,4,5}; 10 for(auto i: ithreads) 11 { 12 thread t1(thread1,i,i+1); 13 t1.join(); 14 }

C++11 thread::detach(2)

原文地址:http://www.cplusplus.com/reference/thread/thread/detach/ public member function <thread> std::thread::detach void detach(); Detach thread Detaches the thread represented by the object from the calling thread, allowing them to execute independen

c++ 11 thread 初试

最新的 c++11标准整合进了 线程支持,下面写一个小程序测试一下. 测试代码: #include <iostream> #include <thread> void hello(void) { std::cout << "Hello concurrent world" << std::endl; } int main(void) { std::thread t(hello); t.join(); } 编译方法: g++ -std=c++

C++11 Thread多线程的学习心得与问题

C++11 ,封装了thread的多线程的类,这样对多线程的使用更加方便. 多线程的原理我不加赘述,可以参看操作系统等参考书. 多线程代码可以最大化利用计算机性能资源,提高代码的运行效率,是常用优化方法. 我不是C++大神,初学阶段的菜鸟而已,很多问题我还是不理解当中的原理,写这篇博客的原因,也是记录自己的学习心得和思路,供自己日后自己思考. 首先从简单的问题入手,如何写一个多线程的C++代码? #include<iostream> #include<thread> void fu

c++11 thread (目前我使用的ZThread库)

目前为止(2014-11-30),GCC其实已经基本上完全支持C++11的所有功能了,事实上从GCC4.7之后,就支持了-std=c++11选项,在4.7版本之前,也开始支持-std=c++0x的选项了 但是目前由于MinGW工作组的问题(没有跟上GNU GCC工作组的步伐,事实上目前GCC已经更新到4.9了,MinGW-Installer中能获取的最新版本的G++还停留在4.8.1版本,不仅如此,尽管是4.8.1,MinGW并没有提供很多C++11应有的功能).(也就是说,你在非Windows

C++11 thread::joinable(5)

原文地址:http://www.cplusplus.com/reference/thread/thread/joinable/ public member function <thread> std::thread::joinable bool joinable() const noexcept; Check if joinable Returns whether the thread object is joinable. 返回线程对象是否是joinable的. A thread objec

C++11 thread::join(4)

原文地址:http://www.cplusplus.com/reference/thread/thread/join/ public member function <thread> std::thread::join void join(); Join thread The function returns when the thread execution has completed. 当该线程执行完成后才返回.(即等待子线程执行完毕才继续执行主线程) This synchronizes