1.Linux下创建进程
1 #include <stdio.h> 2 3 #include <unistd.h> 4 5 int main() 6 7 { 8 9 pid_t pid; 10 11 /* fork a child process */ 12 13 pid = fork(); 14 15 if (pid < 0) { /* error occurred */ 16 17 fprintf(stderr, "Fork Failed"); 18 19 return 1; 20 21 } 22 23 else if (pid == 0) { /* child process */ 24 25 execlp("/bin/ls", "ls", NULL); 26 27 } 28 29 else { /* parent process */ 30 31 /* parent will wait for the child to complete */ 32 33 wait(NULL); 34 35 printf("Child Complete "); 36 } 37 return 0; 38 }
2.Windows下进程创建
1 #include<stdio.h> 2 #include<windows.h> 3 int main() 4 { 5 STARTUPINFO si;//STARTUPINFO用于指定新进程的主窗口特性的一个结构。 6 PROCESS_INFORMATION pi;//在创建进程时相关的数据结构之一,该结构返回有关新进程及其主线程的信息。 7 ZeroMemory(&si, sizeof(si));//ZeroMemory是一个计算机函数,由美国微软公司的软件开发包SDK中的一个宏。 其作用是用0来填充一块内存区域。 8 si.cb = sizeof(si); 9 ZeroMemory(&pi, sizeof(pi)); 10 TCHAR szCommandLine[] = TEXT("C:\Program Files (x86)\Tencent\QQ\Bin\QQ.exe"); 11 //WIN32API函数CreateProcess用来创建一个新的进程和它的主线程,这个新进程运行指定的可执行文件 12 if (!CreateProcess(NULL, 13 szCommandLine, 14 //"c:\windows\system32\mspaint.exe", 15 NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) 16 { 17 printf("Create Process Failed! "); 18 return -1; 19 } 20 else 21 { 22 printf("Parent Hello World! "); 23 } 24 WaitForSingleObject(pi.hProcess, INFINITE);//WaitForSingleObject是一种Windows API函数,当等待仍在挂起状态时,句柄被关闭,那么函数行为是未定义的。 25 printf("Child Process Complete "); 26 printf("Child Process Running "); 27 CloseHandle(pi.hProcess);//CloseHandle包括文件、文件映射、进程、线程、安全和同步对象等。 28 CloseHandle(pi.hThread); 29 return 0; 30 }
3.进程间通信
写内存:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <fcntl.h> 5 #include <sys/shm.h> 6 #include <sys/stat.h> 7 #include <sys/mman.h> 8 int main() 9 { 10 /* the size (in bytes) of shared memory object */ 11 const int SIZE = 4096; 12 /* name of the shared memory object */ 13 const char* name = "OS"; 14 /* strings written to shared memory */ 15 const char* message_0 = "JLU"; 16 const char* message_1 = " Communicating Engineering "; 17 /* shared memory file descriptor */ 18 int shm_fd; 19 /* pointer to shared memory obect */ 20 void* ptr; 21 /* create the shared memory object */ 22 shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); 23 /* configure the size of the shared memory object */ 24 ftruncate(shm_fd, SIZE); 25 /* memory map the shared memory object */ 26 ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); 27 /* write to the shared memory object */ 28 sprintf(ptr, "%s", message_0); 29 ptr += strlen(message_0); 30 sprintf(ptr, "%s", message_1); 31 ptr += strlen(message_1); 32 return 0; 33 }
读内存:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <fcntl.h> 4 #include <sys/shm.h> 5 #include <sys/stat.h> 6 #include <sys/mman.h> 7 int main() 8 {/* the size (in bytes) of shared memory object */ 9 const int SIZE = 4096; 10 /* name of the shared memory object */ 11 const char* name = "OS"; 12 /* shared memory file descriptor */ 13 int shm_fd; /* pointer to shared memory obect */ 14 void* ptr; 15 /* open the shared memory object */ 16 shm_fd = shm_open(name, O_RDONLY, 0666); 17 /* memory map the shared memory object */ 18 ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0); 19 /* read from the shared memory object */ 20 printf("%s", (char*)ptr); 21 /* remove the shared memory object */ 22 shm_unlink(name); 23 return 0; 24 }
4.Pthread线程创建
1 #include <pthread.h> 2 #include <stdio.h> 3 int sum; /* this data is shared by the thread(s) */ 4 void* runner(void* param); /* threads call this function */ 5 int main(int argc, char* argv[]) 6 { 7 pthread_t tid; /* the thread identifier */ 8 pthread_attr_t attr; /* set of thread attributes */ 9 if (argc != 2) { 10 fprintf(stderr, "usage: a.out <integer value> "); 11 return -1; 12 } 13 if (atoi(argv[1]) < 0) { 14 fprintf(stderr, "%d must be >= 0 ", atoi(argv[1])); 15 return -1; 16 } 17 /* get the default attributes */ 18 pthread_attr_init(&attr); 19 /* create the thread */ 20 pthread_create(&tid, &attr, runner, argv[1]); 21 /* wait for the thread to exit */ 22 pthread_join(tid, NULL); 23 printf("sum = %d ", sum); 24 } 25 /* The thread will begin control in this function */ 26 void* runner(void* param) 27 { 28 int i, upper = atoi(param); 29 sum = 0; 30 for (i = 1; i <= upper; i++) 31 sum += i; 32 pthread_exit(0); 33 }
5.Windows线程创建
1 #include <windows.h> 2 #include <stdio.h> 3 #define THREADNUM 3 //线程数 4 int sum; 5 DWORD WINAPI ThreadFunc(LPVOID lpParam) 6 { 7 sum = 0; 8 int upper; 9 memcpy(&upper, lpParam, sizeof(int)); 10 for (int i = 0; i <= upper; i++) 11 sum += i; 12 return 0; 13 } 14 int main(int argc, char* argv[]) 15 { 16 DWORD dwThreadId; 17 HANDLE hThread; 18 int upper; 19 if (argc > 1) 20 { 21 upper = atoi(argv[1]); 22 } 23 else 24 { 25 printf("未输入参数 "); 26 return -1; 27 } 28 29 hThread = CreateThread( 30 NULL, 31 0, 32 ThreadFunc, 33 &upper, 34 CREATE_SUSPENDED, 35 &dwThreadId); 36 ResumeThread(hThread); 37 WaitForSingleObject(hThread, 1000); 38 printf("sum = %d ", sum); 39 return 0; 40 }
6.使用互斥变量进程线程间同步的线程创建
1 #include <atlstr.h> 2 #include <atltime.h> 3 #include <windows.h> 4 #include <stdio.h> 5 #define THREADNUM 10 //线程数 6 HANDLE Mutex; 7 DWORD WINAPI ThreadFunc(LPVOID lpParam) 8 { 9 CTime time = CTime::GetCurrentTime(); 10 CString s = time.Format(time.GetDay()); 11 int len = s.GetLength(); 12 WaitForSingleObject(Mutex, INFINITE); 13 for (int i = 0; i < len; i++) 14 putchar(s.GetAt(i)); 15 int t = time.GetHour(); 16 putchar(' '); 17 if (t < 12) 18 { 19 putchar('A'); 20 } 21 else 22 { 23 putchar('P'); 24 } 25 putchar('M'); 26 putchar(' '); 27 ReleaseMutex(Mutex); 28 return 0; 29 } 30 int main(int argc, char* argv[]) 31 { 32 DWORD dwThreadId[THREADNUM]; 33 HANDLE hThread[THREADNUM]; 34 Mutex = CreateMutex(NULL, false, NULL); 35 for (int i = 0; i < THREADNUM; i++) 36 hThread[i] = CreateThread( 37 NULL, 38 0, 39 ThreadFunc, 40 NULL, 41 CREATE_SUSPENDED, 42 &dwThreadId[i]); 43 for (int i = 0; i < THREADNUM; i++) 44 ResumeThread(hThread[i]); 45 Sleep(500 * THREADNUM); 46 return 0; 47 }
7.用信号灯完成线程互斥、同步实验
#include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> char str[64] = ""; sem_t sem; void* runner(void* threadid) { sem_wait(&sem); printf("hello child:"); printf("%s ", str); pthread_exit(NULL); } int main(int argc, char* argv[]) { pthread_t thread; int rc; long t; sem_init(&sem, 0, 0); rc = pthread_create(&thread, NULL, runner, (void*)t); if (rc) { printf("ERROR; return code from pthread_create() is %d ", rc); exit(-1); } scanf("%s", str); sem_post(&sem); pthread_join(thread, NULL); printf("Parent hello "); pthread_exit(NULL); }
1 #include <pthread.h> 2 #include <semaphore.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 int sharevalue = 0; 6 sem_t sem; 7 void* runner1(void* threadid) 8 { 9 sem_wait(&sem); 10 sharevalue = 0; 11 while (sharevalue < 20) 12 { 13 if (sharevalue % 2 == 0) 14 printf("thread1:%d ", sharevalue); 15 sharevalue++; 16 } 17 sem_post(&sem); 18 pthread_exit(NULL); 19 } 20 21 void* runner2(void* threadid) 22 { 23 sem_wait(&sem); 24 sharevalue = 0; 25 while (sharevalue < 20) 26 { 27 if (sharevalue % 3 == 0) 28 printf("thread2:%d ", sharevalue); 29 sharevalue++; 30 } 31 sem_post(&sem); 32 pthread_exit(NULL); 33 } 34 int main(int argc, char* argv[]) 35 { 36 pthread_t thread1, thread2; 37 int rc; 38 long t; 39 sem_init(&sem, 0, 10); 40 rc = pthread_create(&thread1, NULL, runner1, (void*)t); 41 if (rc) { 42 printf("ERROR; return code from pthread_create() is %d ", rc); 43 exit(-1); 44 } 45 rc = pthread_create(&thread2, NULL, runner2, (void*)t); 46 if (rc) { 47 printf("ERROR; return code from pthread_create() is %d ", rc); 48 exit(-1); 49 } 50 pthread_join(thread1, NULL); 51 pthread_join(thread2, NULL); 52 printf("Parent hello "); 53 pthread_exit(NULL); 54 }