How to pass parameters to the thread functions beginthread and pthread_create

Source: Internet
Author: User

1. Pass a single parameter: directly pass the pointer to the parameter.


/* ----------------------- Beginthread. c ----------------------------*/
# Include <process. h>

Void doubleNum (void * arg)
{
Int * arg = (int *) arg;
* Arg = (* arg) * 2;
}
Void main ()
{
Int arg = 0;
_ Beginthread (doubleNum, 0, (void *) & arg );
}
/* ----------------------- Pthread_create.c ----------------------------*/
# Include <pthread. h>

Void doubleNum (void * arg)
{
Int * arg = (int *) arg;
* Arg = (* arg) * 2;
}
Void main ()
{
Int arg = 0;
Pthread_t thread;
Pthread_create (& thread, 0, doubleNum, (void *) & arg );
Pthread_join (thread, NULL );
}

2. Pass multiple parameters: Define a struct containing all parameters and pass a pointer to the struct.

 

/* ----------------------- StructAndFunc. h ----------------------------*/

# Include <stdio. h>
Struct threadparam
{
Int * arg1;
Char [5] arg2;
}
Void doubleNum (void * arg)
{
Int * arg1 = (threadparam *) arg-> arg1;
Char * arg2 = (threadparam *) arg-> arg2;
Printf ("integer: % d char array: % s \ n", * arg1, arg2 );
}

/* ----------------------- Beginthread. c ----------------------------*/
# Include <process. h>
# Include <StructAndFunc. h>
Void main ()
{
Int integer = 5;
Char [5] array = {a, B, c, d, e };
Threadparam * param = new threadparam ();
Param-> arg1 = & interger;
Param-> arg2 = array;
HANDLE m_hThread = (HANDLE) _ beginthread (doubleNum, 0, (void *) threadparam );
}
/* ----------------------- Pthread_create.c ----------------------------*/
# Include <pthread. h>
# Include <StructAndFunc. h>
Void main ()
{
Int integer = 5;
Char [5] array = {a, B, c, d, e };
Threadparam * param = new threadparam ();
Param-> arg1 = & interger;
Param-> arg2 = array;
Pthread_t thread;
Pthread_create (& thread, 0, doubleNum, (void *) param );
Pthread_join (thread, NULL );
}
Ps. The above code is not tested, and some minor syntax errors may exist.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.