在C中创建动态线程
如何在运行时使用C编程语言创建多线程? 如果我们需要创建与用户指定的相同数量的线程,我们该如何做?在Linux上使用在C中创建动态线程,c,C,如何在运行时使用C编程语言创建多线程? 如果我们需要创建与用户指定的相同数量的线程,我们该如何做?在Linux上使用 #包括 #包括 #包括 void*打印消息功能(void*ptr); int main(int argc,char*argv[]) { pthread_t thread1,thread2; char*message1=“线程1”; char*message2=“线程2”; int iret1,iret2; /*创建独立的线程,每个线程都将执行函数*/ iret1=pthread_
#包括
#包括
#包括
void*打印消息功能(void*ptr);
int main(int argc,char*argv[])
{
pthread_t thread1,thread2;
char*message1=“线程1”;
char*message2=“线程2”;
int iret1,iret2;
/*创建独立的线程,每个线程都将执行函数*/
iret1=pthread_create(&thread1,NULL,print_message_函数,(void*)message1);
iret2=pthread_create(&thread2,NULL,print_message_函数,(void*)message2);
/*等到线程完成后,main才会继续。除非*/
/*等等,我们冒着执行退出的风险,退出将终止*/
/*线程完成之前的进程和所有线程*/
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf(“线程1返回:%d\n”,iret1);
printf(“线程2返回:%d\n”,iret2);
出口(0);
}
void*打印消息功能(void*ptr)
{
字符*消息;
消息=(字符*)ptr;
printf(“%s\n”,消息);
}
检查Windows和linux\include
#包括
#包括
#包括
作废*打印()
{
printf(“\n读取已创建”);
}
int main()
{
int ch,i;
pthread_t*t;
printf(“输入要创建的线程数:”);
scanf(“%d”和“ch”);
t=(pthread_t*)malloc(ch*sizeof(pthread_t));
对于(i=0;iI)您的print\u message\u函数
似乎缺少返回语句?似乎是这样,但它仅在GCC中发出警告,这是因为标准中存在技术性问题,要求实现尝试编译和运行程序。(并非所有的实现都遵循这一要求,但gcc在这种情况下确实遵循了标准的规定。)这与不需要复杂的控制流分析有关,特别是对于可能不会返回的函数(例如abort()、exit()、terminate()、…)。但是,代码是错误的,应该明确地加以修复。可能的dup:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
void *print()
{
printf("\nThread Created");
}
int main()
{
int ch,i;
pthread_t *t;
printf("Enter the number of threads you want to create : ");
scanf("%d",&ch);
t=(pthread_t *)malloc(ch * sizeof(pthread_t ));
for(i=0;i<ch;i++)
{
pthread_create(&t[i],NULL,print,NULL); //Default Attributes
}
for(i=0;i<ch;i++)
{
pthread_join(t[i],NULL);
}
}