如何使螺纹包含循环使用静音以控制流动

How to make a thread contain a loop using mutexes to control flow?

本文关键字:控制流 何使螺 包含 循环      更新时间:2023-10-16

我正在做家庭作业,我已经撞到了墙。分配是在控制Mutex的情况下使用2个线程,以在5个迭代的循环中减少一个数字X。

第一个线程x = x-5
第二个线程x = x/5

适当的结果应从19530将x降低到5个迭代,在每次迭代时之间的螺纹1和thread2之间交替。


到目前为止,我有以下结果:

thread1:x = 19525
线程1:x = 19520
thread1:x = 19515
thread1:x = 19510
thread1:x = 19505


从上方很明显,我的第二个线程不仅不做工作,而且根本没有做任何事情。

以下是我的代码,它是用C 编写的,但是样式使用了我们在课堂上学到的工具,这是一个人在C中的做法,但无论哪种方式都应该使用相同的方式。

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
void *first(void *);
void *second(void *);
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
int x = 19530; // global var that is being manipulated
int i = 1; // counter for the loops
int main() {
    int t1, t2;
    pthread_t thread1, thread2;
    if((t1 = pthread_create( &thread1, NULL, first, NULL))) {
        printf("Thread creation failed: %dn", t2);
    }
    if((t2 = pthread_create( &thread2, NULL, second, NULL))) {
        printf("Thread creation failed: %dn", t2);
    }
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return(0);
}
void *first(void *){ // function for thread1
  for(; i <=5; i++){
  pthread_mutex_lock(&mymutex);
  x = x-5;
  cout << "Thread1: x = " << x << endl;
  pthread_mutex_unlock(&mymutex);
  }
}
void *second(void *){ // function for thread2
  for(; i<=5; i++){
  pthread_mutex_lock(&mymutex);
  x = x/5;
  cout << "Thread2: x = " << x << endl;
  pthread_mutex_unlock(&mymutex);
  }
}

注意,我是概念线程和静音的全新。而且我宁愿坚持我在课堂上学到的方式,我认为这被称为" C方式"。

感谢rclgdr,我在上面评论了我能够回答以下代码按预期工作:

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
void *first(void *);
void *second(void *);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; // thread1 mutex
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; // thread2 mutex
int x = 19530; // global var that is being manipulated
int main() {
    cout << "x = " << x << endl << endl;
    int t1, t2;
    pthread_t thread1, thread2;
    pthread_mutex_lock(&mutex2);
    if((t1 = pthread_create( &thread1, NULL, first, NULL))) {
        printf("Thread creation failed: %dn", t2);
    }
    if((t2 = pthread_create( &thread2, NULL, second, NULL))) {
        printf("Thread creation failed: %dn", t2);
    }
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return(0);
  }
void *first(void *){ // function for thread1
  for(int i = 1; i <=5; i++){
  pthread_mutex_lock(&mutex1);
  x = x-5;
  cout << "Iteration " << i <<endl;
  cout << "Thread1: x = " << x << endl;
  pthread_mutex_unlock(&mutex2);
  }
}
void *second(void *){ // function for thread2
  for(int i = 1; i<=5; i++){
  pthread_mutex_lock(&mutex2);
  x = x/5;
  cout << "Thread2: x = " << x << endl << endl;
  pthread_mutex_unlock(&mutex1);
  }
}