"Go" multithreaded Programming for Windows, C + +

Source: Internet
Author: User

In multithreaded programming in Windows, the functions that create threads are mainly CreateThread and _beginthread (and _beginthreadex).


CreateThread and ExitThread

Use the API function CreateThread to create a thread, where the threading function is prototyped:
DWORD WINAPI ThreadProc (LPVOID lpparameter);
After the thread function returns, its return value is used as an argument to call the ExitThread function (implicitly called by the system). You can use the GetExitCodeThread function to get the return value of the thread function.

The CreateThread function may still return successfully when the start address of the thread function is invalid (or inaccessible). If the starting address is not valid, the exception occurs when the thread runs, and the thread terminates. and returns an error code.

Threads created with CreateThread have a thread priority of Thread_priority_normal. You can use the getthreadpriority and setthreadpriority functions to get and set thread priority values.

The thread object in the system survives until the thread ends, and all the handles to it are closed by calling CloseHandle.

_beginthread and _endthread (_beginthread & _endthread)

Threads that use functions in the C run-time library should use the C run-time functions _beginthread and _endthread to manage threads instead of using CreateThread and ExitThread. Otherwise, a memory leak may be thrown when ExitThread is called.

When you create a thread using _beginthread or _beginthreadex, you should include the header file <process.h&gt, and you need to set up a multithreaded version of the runtime library. "project Settings"-->"c/c++"-->"category"-->"code generation"-->"use Run-Time library"-->" multithreaded"and"debug multithreaded". This is equivalent to adding a compile option/MT to the compilation so that the compiler uses the LIBCMT.lib file name instead of the LIBC.lib in the. obj file at compile time. The connector uses this name to connect to the run-time library function.

You can call _endthread and the _endthreadex display to end a thread. However, when the thread function returns, _endthread and _endthreadex are called automatically. The invocation of Endthread and _endthreadex helps to ensure that the resources allocated to the thread are properly recycled. _endthread automatically closes the thread handle, but _endthreadex does not. Therefore, when you use _beginthread and _endthread, you do not need to display the call API function CloseHandle-close thread handle. This behavior differs from the invocation of the API function ExitThread. After _endthread and _endthreadex reclaim the allocated thread resources, call ExitThread.

When _beginthread and _beginthreadex are called, the operating system handles the assignment of the line stacks itself. If you specify a stack size of 0 when you call these functions, the operating system creates stacks that are the same size as the main thread. If either thread calls Abort, exit, or exitprocess, all threads are terminated.

Thread is the operating system management of a resource, different operating systems vary greatly, some support, some do not support, the implementation of different ways, the following is a reference to the Linux under the multithreading example, usingPthread Library (third party libraries), simply note the following:

/*THREAD_EXAMPLE.C:C multiple thread programming in Linux
*author:falcon
*date:2006.8.15
*e-mail: [Email][email Protected][/email]
*/
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#define MAX 10

pthread_t thread[2]; Create a thread function return type
pthread_mutex_t Mut; Mutex lock type
int number=0, I;

void *thread1 ()//thread function
{
printf ("Thread1:i ' m thread 1\n");

for (i = 0; i < MAX; i++)
{
printf ("Thread1:number =%d\n", number);
Pthread_mutex_lock (&mut); Lock to operate on shared variables
number++;
Pthread_mutex_unlock (&mut); Unlock
Sleep (2);
}


printf ("THREAD1: is the main function waiting for me to finish the task?" \ n ");
Pthread_exit (NULL);
}

void *thread2 ()
{
printf ("Thread2:i ' m thread 2\n");

for (i = 0; i < MAX; i++)
{
printf ("Thread2:number =%d\n", number);
Pthread_mutex_lock (&mut);
number++;
Pthread_mutex_unlock (&mut);
Sleep (3);
}


printf ("THREAD2: is the main function waiting for me to finish the task?" \ n ");
Pthread_exit (NULL);
}

void Thread_create (void)
{
/* Create thread */
Pthread_create (&thread[0], NULL, THREAD1, NULL);
printf ("Thread 1 was created \ n");
Pthread_create (&thread[1], NULL, THREAD2, NULL);
printf ("Thread 2 was created \ n");
}

void thread_wait (void)
{
/* Wait for thread to end */
Pthread_join (Thread[0],null);
printf ("Thread 1 has ended \ n");
Pthread_join (Thread[1],null);
printf ("Thread 2 has ended \ n");
}

int main ()
{
/* Initialize the mutex with default properties */
Pthread_mutex_init (&mut,null);

printf ("I am the main function Oh, I am creating threads, hehe \ n");
Thread_create ();
printf ("I am the main function, oh, I am waiting for the thread to finish the task, hehe \ n");
Thread_wait ();

return 0;
}

Pthread Related:

some configuration needs to be done before running:
1. Download Pthread's Windows Development Kit Pthreads-w32-2-4-0-release.exe (any one version available)
http://sourceware.org/pthreads-win32/, unzip to a directory.
2. Locate the Include and Lib folders, and add them below to the vc++6.0 header file path and the static link library path, respectively:
a). Tools->options, select the Directory page, and then in Show directories for: Select Include files (default) to add the include path in directories. In Show directories for: Select library files,
Add the path to the Lib in the directories.
b). project->settings, select the link page, and then add the *.lib file under Lib to the Object/library Modules,
Each lib file is separated by a space.
c). Copy the *.dll file under Lib to the project directory, which is the root directory.

3. Code

1. #include <stdio.h> 2. #include <stdlib.h> 3. #include <pthread.h> 4. #include <windows.h> 5  .   6.int Piao = 100;   7.8.pthread_mutex_t Mut;   9.10.void* Tprocess1 (void* args) {11.   int a = 0;           The. while (true) {13.   Pthread_mutex_lock (&mut);            if (piao>0) {15.   Sleep (1);   piao--;   In printf ("Windows 1----------------have%d tickets left \ n", Piao);            }else{19.   A = 1;          20.} 21.   Pthread_mutex_unlock (&mut);            if (a = = 1) {23.   Break        24.} 25.           } 26.       27.28.   return NULL;  29.} 30.     31.void* Tprocess2 (void* args) {32.   int a = 0;           The. while (true) {34.   Pthread_mutex_lock (&mut);            if (piao>0) {36.   Sleep (1);   Panax piao--;   printf ("Windows 2----------------with%d tickets \ n", Piao); }else{40.           A = 1;          41.} 42.   Pthread_mutex_unlock (&mut);            if (a = = 1) {44.   Break        45.} 46.           } 47.       48.49.   return NULL;  50.} 51.   52.void* tprocess3 (void* args) {53.   int a = 0;           The. while (true) {55.   Pthread_mutex_lock (&mut);       . if (piao>0) {57.   Sleep (1);   piao--;        59.60.   printf ("Windows 3----------------left%d tickets \ n", Piao);            }else{62.   A = 1;          63.} 64.   Pthread_mutex_unlock (&mut);            if (a = = 1) {66.   Break        67.} 68.           } 69.       70.71.   return NULL;  72.} 73.       74.void* tprocess4 (void* args) {75.   int a = 0;           The. while (true) {77.   Pthread_mutex_lock (&mut);       The. if (piao>0) {79.   Sleep (1);                   80.81.   piao--;        82.  ("Windows 4----------------left%d tickets \ n", Piao);            85.}else{.   A = 1;          86.} 87.   Pthread_mutex_unlock (&mut);            if (a = = 1) {89.   Break        90.} 91.           } 92.       93.94.   return NULL;  95.} 96.  97.int Main () {98.   Pthread_mutex_init (&mut,null);   pthread_t T1;   pthread_t T2;   101. pthread_t T3;   102. pthread_t T4;   103. Pthread_create (&t4,null,tprocess4,null);   104. Pthread_create (&t1,null,tprocess1,null);   Pthread_create (&t2,null,tprocess2,null);   106. Pthread_create (&t3,null,tprocess3,null);   107. Sleep (5000);   108. return 0;   109.}

"Go" multithreaded Programming for Windows, C + +

Related Article

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.