#include<atomic>
#include<thread>
class CountDownload{
private:
std::atomic<int> number;
public:
CountDownload(int num);
void await();
void dwonload();
};
CountDownload::CountDownload(int num){
number.exchange(num);
}
void CountDownload::await(){
while(number > 0){
std::this_thread::yield();
}
}
void CountDownload::dwonload(){
number--;
}
#include<iostream>
#include<atomic>
#include<thread>
#include<vector>
#include<pthread.h>
#include<mutex>
#include"CountDwonload.cpp"
using namespace std;
std::atomic<bool> reay(false);
std::atomic<int> number(0);
std::atomic<bool> winner(false);
std::mutex mymutex;
CountDownload mCountDownload(10);
void* hello(void* id){
while(!reay){
}
for (size_t i = 0; i < 10000000; i++)
{
/* code */
}
std::cout << "结束!" << *((int *) id) << std::endl;
mCountDownload.dwonload();
free(id);
return NULL;
}
int main(int argv,char ** argc){
pthread_t threads[10];
for (size_t i = 0; i < 10; i++)
{
int* m = (int *)calloc(1,sizeof(int));
*m = i;
pthread_create(&threads[i],NULL,hello,m);
}
reay = true;
mCountDownload.await();
std::cout << "结束!" << std::endl;
return 0;
}
gangzhoudeAir:~ gang.zhou$ ./Hello
结束!3
结束!6
结束!7
结束!0
结束!5
结束!4
结束!2
结束!1
结束!8
结束!9
结束!
gangzhoudeAir:~ gang.zhou$
网友评论