zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Luogu p2672 推销员 (贪心)
    HDU 1548 A strange lift (暴力搜索)
    HDU 1258 Sum it up (dfs)
    HDU 1087 FatMouse and Cheese (记忆化搜索)
    Beautiful Numbers(牛客)
    E. Product Oriented Recurrence(矩阵快速幂+欧拉降幂)
    Super A^B mod C FZU
    bitset入门 简单瞎搞题
    D. Dirty Deeds Done Dirt Cheap(思维)
    大家一起来数二叉树吧(DP)
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8689175.html
Copyright © 2011-2022 走看看