Skip to content

Commit b08b7e1

Browse files
committed
small test
1 parent ad8f450 commit b08b7e1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

doc/test_thread.cpp

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// g++ -o out_test_thread test_thread.cpp -lpthread -std=c++11
2+
#include<stdio.h>
3+
#include<iostream>
4+
// #include<pthread.h>
5+
#include<thread>
6+
#include<string.h>
7+
#include<stdlib.h>
8+
#include<mutex>
9+
10+
// void *f(void *t) {
11+
// int *num = (int*) t;
12+
// printf("t_print num=%d\n", *num);
13+
// pthread_exit(NULL);
14+
// }
15+
// int main(int n, char *argv[]) {
16+
// printf("===test==\n");
17+
// int arr[5] = {1, 2, 3, 4, 5};
18+
// pthread_t threads[5];
19+
// int r;
20+
// for(int i=0;i<5;i++) {
21+
// r = pthread_create(&threads[i], NULL, f, (void*)(&arr[i]));
22+
// if(r) {
23+
// std::cout << "pthread_create fail, r=" << r << std::endl;
24+
// exit(-1);
25+
// }
26+
// }
27+
// pthread_exit(NULL);
28+
// return 0;
29+
// }
30+
31+
int cnt = 0;
32+
std::mutex m;
33+
void f1(int *num) {
34+
std::lock_guard<std::mutex> lock(m);
35+
// m.lock();
36+
*num = 100;
37+
(*num)++;
38+
printf("f1 num=%d threadid=%ld\n", *num, std::this_thread::get_id());
39+
// m.unlock();
40+
}
41+
void f2(int *num) {
42+
std::lock_guard<std::mutex> lock(m);
43+
// m.lock();
44+
*num = 200;
45+
(*num)--;
46+
printf("f2 num=%d threadid=%ld\n", *num, std::this_thread::get_id());
47+
m.unlock();
48+
}
49+
int main(int n, char *argv[]) {
50+
printf("===test==\n");
51+
std::thread t1(f1, &cnt);
52+
std::thread *t2 = new std::thread(f2, &cnt);
53+
t1.join();
54+
t2->join();
55+
return 0;
56+
}

0 commit comments

Comments
 (0)