如何直接在主要功能中使用锁

时间:2019-11-26 17:36:19

标签: c++ multithreading locking

在我的主要功能中,我正在尝试实现类似于以下内容的多线程

#include <thread>
#include <mutex>
....

int main(int argc, char *argv[])
{
    std::mutex myMutex;

    while(...) {
       //some code
       std::thread t1([=,&myArr](){
          std::lock_guard<std::mutex> lockGuard(myMutex);
          for(int i=0; i<1000; i++) {
              myArr[i] = alpha*(myArr[i] - t*myArr[i-1]) ;
          }
       });

       std::thread t2([=,&myArr](){
           std::lock_guard<std::mutex> lockGuard(myMutex);
           for(int i=1000; i<2000; i++) {
               myArr[i] = alpha*(myArr[i] - t*myArr[i-1]) ;
           }
       });
       t1.join();
       t2.join();

    }

    return 0;
}

当我运行类似myArr数组的代码时,并没有按照我的意愿进行更新。由于种族条件。 ‘lock_guard’可以帮助我通过网络搜索解决此问题。但是我对如何将其添加到这段代码中有些困惑。我尝试直接添加如下内容:

{
   t1.join();
   std::lock_guard<std::mutex> lockGuard(myMutex);
}
{
   t2.join();
   std::lock_guard<std::mutex> lockGuard(myMutex);
}

但是它给出了错误:mycode.cpp:2127:错误:将类型'std :: lock_guard :: mutex_type&{aka std :: mutex&}'的引用绑定到'const std :: mutex'会丢弃限定符std :: lock_guard lockGuard(myMutex);

有什么聪明的方法可以解决这个问题?

1 个答案:

答案 0 :(得分:2)

您的代码中有两个问题可能会导致编译错误,但是可以通过按引用捕获互斥锁来解决。就目前而言,您的代码正在尝试按值捕获互斥锁,因为该互斥锁包含在默认值package assignment.pkg1; import java.util.Scanner; public class Assignment1 { public static void main(String[] args) { controller(); } //----------------------------controller()-------------------------------------- public static void controller() { Scanner kb = new Scanner(System.in); double num[]=new double[10], cel, fah, tem; char ch; for(int x=0; x<10; x++) //This loops ten times to get ten tempretures { System.out.print("Please enter your tempreture :"); num[x]=kb.nextDouble(); } System.out.println(); System.out.println("Is the data you are entering in Fahrenheit or Celcius?"); System.out.println("Please enter C for Celcius or F for Fahrenheit : "); ch = kb.nextLine().charAt(0); if (ch !='C' || ch !='c') { for(int x =0;x<10;x++) { fah=ctof(num[x]); System.out.println(num[x]+" degrees C = "+fah+" degrees F"); } } if (ch =='F' || ch =='f') { for(int x =0;x<10;x++) { cel=ftoc(num[x]); System.out.println(num[x]+" degrees F = "+cel+" degrees C"); } } } //----------------------------ctog()-------------------------------------------- public static double ctof(double cel) { double tem; //fah = cel / 5 + 32; tem = (cel / 5) + 32; return tem; } //----------------------------ftoc()-------------------------------------------- public static double ftoc(double fah) { double tem; //cel = (fah - 32)/9 * 5 tem = (fah - 32) /9 * 5; return tem; } } 下。

第一个问题是互斥锁不能通过值捕获,因为互斥锁不可复制。第二个问题是,即使您可以按值捕获互斥锁,捕获的互斥锁也将位于lambda主体内的=内,这意味着它无法被锁定。 (实际上,您无法对指向const的{​​{1}}进行 。)

同样,这两个问题都可以通过引用来解决。 (尽管生成的代码仍然没有意义,因为它似乎迫使两个线程串行运行。)