Yang Huang wrote:
Hi list,
I am currently trying to simulate a situation that two
processes/threads competing for the CPU resource. A lot of examples
and articles have metioned this issue. However, when I tried this with
"pthread_create" and "fork", neither of them works!
The platfrom is Linux 2.6.10, uClibc 3.3.5, my root file system is
built with Buildroot 1.0. The processor is VIA Eden ESP 6000.
Part of the code using fork is listed below:
childpid = fork();
if (childpid >= 0)
{
if (childpid == 0)
{
for (i=0; i<3; i++)
{
printf("mark 1!\n");
}
exit(0);
}
}
else
{
for (i=0; i<3; i++)
printf("mark 2!\n");
wait(&status);
exit(0);
}
as for pthread_create, part of the code is like this:
void thread(void)
{
for(i=0;i<3;i++)
printf("mark 2!\n");
}
int main(void)
{
ret=pthread_create(&id,NULL,(void *) thread,NULL);
for(i=0;i<3;i++)
printf("mark 1!\n");
pthread_join(id,NULL);
}
Whenever I run, both two codes give the same output:
mark 1!
mark 1!
mark 1!
mark 2!
mark 2!
mark 2!
which indicates that there is always the case that only when one
process/thread finishes can the other be given the CPU to continue. Is
that correct? How can I simulate the competition then?
Thank you in advanced for any suggestions!
regards,
Yang
a loop of 3 is too small. the parent process executes the loop and
prints all the numbers and then the child begins.
If you want to see a compete between the 2 processes you have several
solutions.
A process (or a thread) can be preempted if :
_ his quantum (the time this process can be executed) is finished
_ the process frees explicitely the cpu (see man 2 sched_yield)
_ if the process blocks (on an I/O, a semaphore ...)
_ if the process makes a system call
So in your case, you could do a bigger loop (the parent process will be
preempted by the child).
Or you could add a sched_yield() at each cycle of the loop to free the
cpu (note that sched_yield() is a POSIX function and so must be use with
POSIX threads)
These 2 solutions should work.
--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive: http://mail.nl.linux.org/kernelnewbies/
FAQ: http://kernelnewbies.org/faq/