#include <thread>
#include <iostream>
using namespace std;
int shared_value = 0;
void change_value (int n){
for (int i = 0; i < n; i++){
shared_value++;
}
}
int main (){
thread t[100];
for (int i = 0; i < 100; i++){
t[i] = thread (change_value, 1000);
}
for (int i = 0; i < 100; i++){
t[i].join();
}
cout << shared_value << endl;
return 0;
}
编译命令 g++ -std=c++11 - main.cpp -o main -pthread
小爬虫
#include <bits/stdc++.h>
using namespace std;
string url[4] = {
"http://www.baidu.com",
"http://www.ismdeep.com",
"http://www.chinaedu.edu.cn/",
"http://www.neea.edu.cn/"
};
void get_html_content (string _url){
char bash[100] ={"wget \""}, a[100], b[]="\"";
for(int i = 0; _url[i]; i++){
a[i] = _url[i];
}
strcat(bash, a);
strcat(bash, b);
system(bash);
}
int main (){
thread t[100];
for (int i = 0; i < 4; i++){
t[i] = thread(get_html_content,url[i]);
t[i].join();
}
return 0;
}