3.原子变量

全局变量,多线程操作不安全,可能会导致结果不安全

互斥锁,操作很慢,但是结果正确

原子变量,操作很快,结果正确

 

代码示例

 1 #include <Windows.h>
 2 #include <thread>
 3 #include <iostream>
 4 #include <tuple>
 5 using namespace std;
 6 
 7 void run()
 8 {
 9     MessageBox(0, L"hello", L"hello", 0);
10 }
11 
12 void runA(const wchar_t *s, const wchar_t *b)
13 {
14     MessageBox(0, s, b, 0);
15 }
16 
17 class myclass
18 {
19 public:
20     void operator()()//C++重载
21     {
22         MessageBox(0, L"hello", L"hello", 0);
23     }
24 };
25 
26 void main1()
27 {
28     thread t1[3]{ thread(run),thread(run),thread(run) };
29 
30     thread *p1 = new thread(run);
31     thread *p2 = new thread(run);
32 
33     thread *p(new thread[3]{ thread(run),thread(run),thread(run) });
34     //伪函数
35     thread t3[3]{ thread(myclass()),thread(myclass()) ,thread(myclass()) };
36     system("pause");
37 }
38 
39 void main()
40 {
41     //多线程带参数
42     thread t1(runA, L"木头人1", L"HELLO");
43     thread t2(runA, L"木头人1", L"HELLO");
44     thread t3(runA, L"木头人1", L"HELLO");
45 
46     //tuple数组
47     char ch = 'X';
48     short sh = 129;
49     int num = 1234;
50     char *p = "木头人";
51     tuple<char, short, int, char *>mytuple(ch, sh, num, p);
52     auto i0 = get<0>(mytuple);
53     cout << i0 << endl;
54     auto i1 = get<1>(mytuple);
55     cout << i1 << endl;
56     auto i2 = get<2>(mytuple);
57     cout << i2 << endl;
58     auto i3 = get<3>(mytuple);
59     cout << i3 << endl;
60     cin.get();
61 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8689175.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值