pthread Question

Started by
0 comments, last by CmpDev 15 years, 4 months ago
I'm learning how to use pthreads for the first time, trying to use a Round Robin scheduling setup:

#include <pthread.h>
#include <iostream>
using namespace std;

void* client(void* ptr)
{
	for(int i = 0; i < 1000000; i++)
	{
		cout << "client " << i << endl;
	}
}

void* server(void* prt)
{
	for(int i = 0; i < 1000000; i++)
	{
		cout << "server " << i << endl;
	}
}

int main()
{
	pthread_t client_thread, server_thread;
	pthread_attr_t client_attr, server_attr;
	pthread_attr_init(&client_attr);
	pthread_attr_init(&server_attr);
	//pthread_attr_setscope(&client_attr, PTHREAD_SCOPE_SYSTEM);
	//pthread_attr_setscope(&server_attr, PTHREAD_SCOPE_SYSTEM);
	pthread_attr_setschedpolicy(&client_attr, SCHED_RR);
	pthread_attr_setschedpolicy(&client_attr, SCHED_RR);
	pthread_create(&client_thread, &client_attr, &client, 0);
	pthread_create(&server_thread, &server_attr, &server, 0);
	pthread_join(client_thread, NULL);
	pthread_join(server_thread, NULL);
	cout << "Done" << endl;
	return 0;
}

On my computer, the "client" thread runs for 20-30 seconds, followed by the "server" thread. The execution appears to be completely serial in that regard. "Done" is spit out at the end as expected. I'm a little boggled as to why the "server" thread is waiting for the "client" thread to complete. 20 seconds, from my understanding, should be far beyond any time slice. I'm not too concerned with exact equal execution, but I'm concerned about thread starvation. Help is appreciated.
Check out Drunken Brawl at http://www.angelfire.com/games6/drunken_brawl!
Advertisement
It has been a while since I used Pthreads but
You are not checking any return errno from the functions to see if anything failed. For example pthread_attr_setschedpolicy may fail as you are using the default of the calling thread to pthread_attr_init. If the calling thread does not have PTHREAD_EXPLICIT_SCHED defined then it will take no notice of your call to set the policy.
Try calling pthread_attr_getinheritsched if it returns PTHREAD_INHERIT_SCHED then set to PTHREAD_EXPLICIT_SCHED with pthread_attr_setinheritsched

This topic is closed to new replies.

Advertisement