C + + Multithreading debugging Tips

Source: Internet
Author: User

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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.