Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today with a c++ do small procedures to teach you some multithreading related knowledge. First of all, the function of this small program is to simulate the laundry room. There are 6 machines in the laundry room, and each machine can count down independently. In the main thread, you can choose to perform laundry operation on the machine that does not wash clothes, while the machine that does laundry, that is, the machine in the countdown, cannot operate.

Struct TstuParam {int n; };Copy the code

First, we use a structure that defines a thread-pass parameter.

TstuParam MyParam;
MyParam.n=10;
HANDLE hThread = CreateThread(NULL, 0, d, &MyParam, 0, NULL);
Copy the code

Assign the struct parameter to 10, i.e. tell the machine to count down 10 seconds.

D here is the thread function

DWORD WINAPI d(LPVOID lpParamter) {TstuParam* Param = (TstuParam)lpParamter; int n = Param->n; int t,i=0; t=time(NULL); do{ if(t! =time(NULL)){ i++; if(i>n){ break; } clearline(1); Printf (" and %d seconds \n",n-i); } t=time(NULL); //system("cls"); } while(1); return 0L; }Copy the code

The thread function needs to be written independently, in the format shown above. It’s just doing a reverse.

int lefttime[6]={-1,-1,-1,-1,-1,-1};
Copy the code

We use LeftTime to store the time needed to count down, if the machine has not started, then do not count down.

Void PrintTime () {cout < < "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- welcome to the cleaner's reservation system -- -- -- -- -- -- -- -- -- -- -- -- -- -" < < endl; for(int i=0; i<6; I ++) {cout<<" washer "<< I +1<<":"; If (lefttime[I]==-1) {cout<<" not started "; } else if (lefttime[I]==0) {cout<<" finish "; } else { cout<<lefttime[i]<<""; } cout<<endl; } cout<<" Please select the washing machine you want to operate "<<endl; }Copy the code

Finally, print whether each washing machine has been started, and carry out their own countdown.

The final effect is as shown in the figure above. Washing machine 1 has finished washing clothes, washing machine 2 and 3 are in the process of cleaning, and the remaining washing machines are not started.