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 }
  • 相关阅读:
    anaconda安装TensorFlow
    复习NLP-实战(三)
    复习NLP-实战(二)
    复习NLP-实战(一)
    python爬虫实战
    WebSocket实战(一)
    不上传图片直接本地预览
    oracle导出
    使用正则表达式验证学习成绩分数
    限制文本框,文本域输入的字符数量
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8689175.html
Copyright © 2011-2022 走看看