Multithreaded programming, the various threads share data, locks caused by countless bugs, debugging difficulty arises spontaneously, recently felt in a bug debugging, summed up.
1. Find out where the problem is
The most multithreading problem is memory access problem, find a conflict of memory access code block, increase the log output. When each thread is accessed, the output logs and the problem is found.
In general, the problem is due to the incorrect use of the lock or condition variable, or the wrong judgment condition. Find the problem first.
2. Use breakpoints to debug
If the analysis log is not easy to solve the problem, increase the breakpoint information for debugging. From where to fall, from where the breakpoint. Points are interrupted at the point of access to key code points in each thread.
After the program has been paused, the careful analysis judgment condition is wrong, then can through various debugging means to carry on the analysis. If you judge the wrong conditions, then carefully analyze which place the code is wrong. Narrow it down in a step-by-step way.
To give an example, let's talk about the problem of this program:
The goal is to open 10 threads, and so the thread is all over, the main program to exit.
#include <pthread.h>
#include <iostream>
#include <Windows.h>
pthread_cond_t cond = Pthread_cond_initializer;
pthread_mutex_t lock = Pthread_mutex_initializer;
int threadnum = 0;
void* ThreadFunc (void* arg) {
//do Something Sleep
(3000);
Pthread_mutex_lock (&lock);
threadnum--;
Pthread_cond_signal (&cond);
Pthread_mutex_unlock (&lock);
}
int main (int argc, char** argv) {
pthread_t ntid;
Threadnum = ten;
for (int i=0; i<10; i++) {
pthread_create (&ntid, NULL, THREADFUNC, NULL);
}
Pthread_mutex_lock (&lock);
if (threadnum!= 0) {
pthread_cond_wait (&cond, &lock);
std::cout<< "threadnum=" << threadnum << Std::endl;
}
Pthread_mutex_unlock (&lock);
return 0;
}