Unix Programming - mulit-thread's problem

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > May 2006 > mulit-thread's problem





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author mulit-thread's problem
DaVinci

2006-05-10, 1:17 pm

//This is my first multi-thread programme
//Q1:how to debug the new thread(not main thread) ,when I set
breakpoint at funtion thr_fn() and want to step
//into function printids,but it doesn't work.it exit directly.
// Q2:when I debug ,the output is
// new thread global = 1,
/*new thread: pid 8017
tid 3084123056 (0xb7
d3fbb0)
----------
new thread: global =1
main thread: pid 8017
tid 3084126432 (0xb7
d408e0)
----------
main thread:global =2
*/
//but when I run directly and the output is
/*
apple@40years:~/test$ ./pthread
main thread: pid 8026 tid 3083938016 (0xb7d128e0)
----------
new thread: pid 8026 tid 3083934640 (0xb7d11bb0)
----------
main thread:global =2
new thread: global =2

*/
//why the result is different for the varibale global?
//and I think the result got by debug maybe more reasonable,is it
right?
//Q3:man -k pthread_create,
//I can't find the function pthread_xxxxx 's manual.
//what's the problem?I had installed a lots of man pages,I can find the
manpages of fork ,waitpid() and so on
//any help is appreciated,thanks very much.I am sorry for my poor
english
#include<unistd.h>
#include <pthread.h>
#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;

int global = 0;
pthread_t ntid;
void
printids(const char *s)
{
pid_t pid;
pthread_t tid;

pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
cout<<"----------"<<endl;
global =global + 1;
usleep(1000000);

printf("%s",s);
cout<<"global ="<<global<<endl;
}
void *
thr_fn(void *arg)
{
printids("new thread: ");
return((void *)0);
}
int
main(void)
{
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
std::cout<<"pthread_create"<<std::endl;
//--------------------
printids("main thread:");
sleep(1);
exit(0);
}

Nils O. Selåsdal

2006-05-11, 1:20 am

DaVinci wrote:
> //This is my first multi-thread programme
> //Q1:how to debug the new thread(not main thread) ,when I set
> breakpoint at funtion thr_fn() and want to step
> //into function printids,but it doesn't work.it exit directly.

That's because your application terminates when main returns.
It does not wait for all threads to terminate.
Make your main thread sleep longer.
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com