2016-12-28 11 views
-1

mon_param выделяется память основным процессом, вызывающим функцию потока. Эта функция будет вызываться несколькими потоками. Итак, могу ли я смело предположить, что она является потокобезопасной, поскольку я использую только переменные в стеке?В приведенном ниже коде: get_row_of_machine, получающий mon_param в качестве параметра потокобезопасным?

struct table* get_row_of_machine(int row_num,struct mon_agent *mon_param) 
{ 
    struct table *table_row = mon_param->s_table_rows; 
    if(row_num < mon_param->total_states) 
    { 
     table_row = table_row + row_num;   
    } 
    return table_row; 
} 


//in the main function code goes like this .... 
int main() 
{ 
    int msg_type,ret; 
    while(!s_interrupted) 
    { 

     inter_thread_pair = zsock_new(ZMQ_PAIR); 
     if(inter_thread_pair != NULL) 
      zsock_bind (inter_thread_pair, "inproc://zmq_main_pair"); 

      int ret_val = zmq_poll(&socket_items[0], 1, 0); // Do not POLL indefinitely. 
      if(socket_items[0].revents & ZMQ_POLLIN) 
      { 
       char *msg = zstr_recv (inter_thread_pair); // 
       if(msg != NULL)  
       { 
        struct mon_agent *mon_params; 
        //This is where mon_params is getting its memory 

        mon_params = (struct mon_agent*)malloc(sizeof(struct mon_agent)); 
        msg_type = get_msg_type(msg); 

        if(msg_type == /*will check for some message type here*/) 
        { 
         struct thread_sock_params *thd_sock = create_connect_pair_socket(thread_count); 
         // copy the contents of thread_sock_params and also the mon_params to this struct 

         struct thread_parameters parameters; 
         parameters.sock_params = thd_sock; 
         parameters.params = mon_params; //mon_params getting copid here. 

         //Every time I receive a particular message, I create a new thread and pass on the parameters. 
         //So, each thread gets its own mon_params memory allocated. 


        ret = pthread_create(&thread,NULL,monitoring_thread,(void*)&parameters); 

        and then it goes on like this. 

        } 

       }  

      } 


     and the code continues..... there is a breakpoint somewhere down.. 
    } 

} 

void* mon_thread(void *data) 
{ 

    // First time data is sent as a function parameter and later will be received as messages. 
    struct thread_parameters *th_param = (struct thread_parameters *)data; 
    struct mon_agent *mon_params = th_param->params; 

    zsock_t* thread_pair_client = zsock_new(ZMQ_PAIR); 
    //printf("Value of socket is %s: \n",th_param->socket_ep); 
    rc = zsock_connect(thread_pair_client,th_param->sock_params->socket_ep); 
    if(rc == -1) 
    { 
     printf("zmq_connect failed in monitoring thread.\n"); 
    } 

    while(!s_interrupted) 
    { 
     int row; 
     //logic to maintain the curent row. 
     //also receive other messages from thread_pair_client czmq socket. 
     run_machine(row,mon_params);     

    } 

} 


void run_machine(int row_num, struct mon_agent *mon_params) 
{ 
    struct table* table_row = get_row_of_state_machine(row_num,mon_param); 
} 
+1

Нет, вы не можете этого допустить. 'mon_param' - это локальная переменная, но не то, на что она указывает. Поэтому, если другой поток изменит любое из значений, указывающих на вас, вы получите непредсказуемые результаты. – kaylum

+0

извините .. для type. Это на самом деле mon_param, а не «mon». Мне пришлось изменить его обратно из-за изменения, которое я сделал для возвращаемого значения. – Entwickler

+0

Не имеет значения. Имя параметра не имеет никакого отношения к тому, что код не является потокобезопасным. – kaylum

ответ

0

Короче, нет.

Способ обеспечения безопасности потоков по потоку - по дизайну.

Существует нет дурака, способного сделать это или эмпирическое правило. Если вы хорошо знаете свой код, и вы знаете, ни одна другая нить не будет обращаться к одной и той же структуре, а затем, возможно, потокобезопасна.

Если вы знаете какой-то другой поток может попытаться получить доступ к структуре вы можете использовать все виды примитивов синхронизации как mutexes, critical sections, semaphores или в более общем locks.