Q: Bug of PThread? [message #153261] |
Wed, 07 September 2005 04:14  |
Eclipse User |
|
|
|
Hi!
There is my program about PThread which is developed under
Eclipse+CDT+Cygwin Env.
---------------------------------
#include <pthread.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#define THREAD_MAX_NUM 10
int send_num;
int send_count;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_t thread[THREAD_MAX_NUM];
char test[10][10];
void *sub_thread(){
int subnum;
pthread_mutex_lock(&mut);
send_num++;
subnum=send_num;
printf("Sub thread %d begin\n",send_num);
pthread_mutex_unlock(&mut);
sleep(3); //It's the case.
printf("Thread %d down\n",subnum);
}//sub_thread
int create_thread(){
int i=0,temp;
pthread_t threadid[THREAD_MAX_NUM];
for(i=0;i<THREAD_MAX_NUM;i++)
pthread_create(&thread[i],NULL,sub_thread,NULL);
}//Create_thread
int main( int argc,char* argv[]){
int i=0,thnum;
send_num = 0;
printf("Create %d thread \n",THREAD_MAX_NUM);
pthread_mutex_init(&mut,NULL);
thnum = create_thread();
printf("all down\n");
}//main
--------------------------------
This is the result of running below:
Create 10 thread
Sub thread 1 begin
Sub thread 2 begin
Sub thread 3 begin
Sub thread 4 begin
Sub thread 5 begin
Sub thread 6 begin
Sub thread 7 begin
Sub thread 8 begin
Sub thread 9 begin
Sub thread 10 begin
all down
--------------------------
But the function "sleep(3)" in the sub_thread() dose not take effect--it
seems do not sleep. Why? Is it a Bug?
But,when I add a sleep(1) to create_thread() like:
for(i=0;i<THREAD_MAX_NUM;i++){
pthread_create(&thread[i],NULL,sub_thread,NULL);
sleep(1);
}
It result is:
Create 10 thread
Sub thread 1 begin
Sub thread 2 begin
Sub thread 3 begin
Thread 1 down
Sub thread 4 begin
Thread 2 down
Sub thread 5 begin
Sub thread 6 begin
Thread 3 down
Sub thread 7 begin
Thread 4 down
Thread 5 down
Sub thread 8 begin
Thread 6 down
Sub thread 9 begin
Thread 7 down
Sub thread 10 begin
Thread 8 down
all down
---------------------------
It seems all right.
zhengzj@mail.si.net.cn
2005-09-07
Thanks!
|
|
|
Re: Q: Bug of PThread? [message #153282 is a reply to message #153261] |
Wed, 07 September 2005 13:07  |
Eclipse User |
|
|
|
This isn't an Eclipse issue.
I didn't read your code in detail, but it looks like it starts a bunch of
threads, each of which sleeps after being started. While the "sub"
threads sleep, the main continues, launches the next thread, etc. This is
correct but apparently not what you intended.
|
|
|
Powered by
FUDForum. Page generated in 0.04350 seconds