这事Windows下多线程并行计算的程序的框架,代码如下所示:
点击(此处)折叠或打开
- #include <stdio.h>
- #include <windows.h>
- int array[50];
- DWORD WINAPI ComputeProc(LPVOID lp)
- {
- int i;
- int *p;
- p = (int *)lp;
- i = *(int *)lp;
- printf("thread %d running.\n", i);
- array[i] = 2*array[i];
-
- free(p);
- return 0;
- }
- void ComputeF()
- {
- int i = 0;
- HANDLE handle[50];
-
- for(i = 0; i < 50; i++)
- {
- int *itmp = (int *)malloc(sizeof(int));
- *itmp = i;
- handle[i] = CreateThread(NULL, 0, ComputeProc, itmp, 0, 0);
- //Sleep(10);//??10??
- }
- for(i = 0; i < 50; i++)
- {
- WaitForSingleObject(handle[i],INFINITE);
- }
- for(i = 0; i < 50; i++)
- {
- CloseHandle(handle[i]);
- }
- printf("all threads execute complete.\n");
- }
- int main()
- {
- int i = 0;
- for(i = 0; i < 50; i++)
- {
- array[i] = i;
- }
-
- ComputeF();
-
- for(i = 0; i < 50; i++)
- {
- printf("%d ", array[i]);
- }
- return 0;
- }