C++11多线程学习1中,使用的函数是全局函数。

如果换成类函数又怎么样呢?

看下面的例子:

#include <iostream>
#include <windows.h>
#include <thread>

class test
{
public:
	test() {}
	~test() {}

public:
	void testcout(const std::string& str, int time)
	{
		for (int i = 0; i < 10; i++)
		{
			Sleep(time);
			std::cout << str.c_str() << i << std::endl;
		}
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	test te;
	std::thread t1(&test::testcout, te, "t1", 1000);
	std::thread t2(&test::testcout, te, "t2", 1300);
	t1.join();
	t2.join();

	char ch;
	std::cin >> ch;
	return 0;
}

运行结果依旧如下: 结果1

注意,**std::thread t1(&test::testcout, te, “t1”, 1000);**第一个参数已经不是函数的第一个参数了。

当使用类成员函数的时候,第一个参数变成了该类的对象。

那么线程是不是调用的当前对象呢???

#include <iostream>
#include <windows.h>
#include <thread>

class test
{
public:
	test() { n = 0; }
	~test() {}

public:
	void testcout(const std::string& str, int time)
	{
		for (int i = 0; i < 10; i++)
		{
			Sleep(time);
			std::cout << str.c_str() << i << std::endl;
			n++;
		}
		std::cout << str.c_str() << &n << std::endl;
	}

private:
	int n;
};

int _tmain(int argc, _TCHAR* argv[])
{
	test te;
	std::thread t1(&test::testcout, te, "t1", 500);
	std::thread t2(&test::testcout, te, "t2", 700);
	t1.join();
	t2.join();

	char ch;
	std::cin >> ch;
	return 0;
}

其结果是 结果2

注意:如果不写n++的话,由于编译器优化,两个线程可能指向同一个地址。

由此可见,两个线程各自拥有各自的对象。

其实在thread开始的时候,是对该类的对象进行了拷贝。

所以,创建完线程以后,你再对对象进行任何操作,都不会影响到线程里面了。

当然,对象复制用的是浅拷贝。所以如果类里面有引用或者指针的话要特别小心资源释放问题哟。