Q1) Имам приложение, което изпълнява функции, както е показано по-долу. Имах нужда от механизъм за изчакване на отговора въз основа на променливата за глобален брой. Дотогава всяка извикана нишка е заспала.
Отг. Можем да използваме структура, която да изпратим като аргументи на pthread_create()
typedef args
{
int arg;
int gcount;
}sargs;
sargs threadarg[3];
int main()
{
/** Pass the structure after initializing to pthread_create() and access
these values when required*/
}
Q2) Мога ли да обвържа всяка нишка с една и съща функция без условия за състезание.?
Отг. да
Псевдо код:
int gcount[3];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
main()
{
pthread_t th[3];
int arg[3];
gcount[0]=10;
gcount[1]=10;
gcount[2]=10;
// arg array is filled up with 3 different data values
// "same_func()" function is used to invoke the threads with different arg' values
for( i =0; i< 3; i++)
pthread_create(&th[i], NULL, same_func, arg[i]);
for( i = 0;i <3; i++ )
pthread_join(th[i], NULL)
return 0;
}
void same_func( void *val)
{
//Perform sending of this val using send() function for 10 times in each thread.
// Basically I will be sending some specific data along with "val"
//This part is troubling me.
// I need to wait on until the global count decreases based on callback function as shown
// I am not sure of using "gcount" variable in this way. Wants inputs in here.
while( gcount[0] > 0 || gcount[1] > 0 || gcount[2] >0 )
sleep(1);
pthread_exit(NULL);
}
// This function is invoked when I receive response to the above send()
void callback( void *val)
{
//Performs some work
pthread_mutex_lock(&lock);
if(val == arg[0])
gcount[0]--;
if(val == arg[1])
gcount[1]--;
if(val == arg[2])
gcount[2]--;
pthread_mutex_unlock(&lock);
}
Q3) Освен това, когато извикам pthread_join().. Ще изчака ли, докато моята нишка продължи да чака. Или ще върне някаква стойност за грешка и ще направи нишката "зомби"??
Отг. Pthread_join() ще се присъедини безопасно към тази "работна" нишка, извикана към така наречената "главна" нишка, откъдето тази нишка се извиква.
Моля, уведомете ме, ако са необходими допълнителни данни, за да отговорите. Благодаря. Проверете Ans. събрани от дадените отговори.