如何在C中使用线程创建一个简单的程序?
问题描述:
我在C开发新的,我知道,只是基础知识,我需要创建一个发现一个简单的哈希密码,这样一个程序:如何在C中使用线程创建一个简单的程序?
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <crypt.h>
#include <stdlib.h>
#define SIZE_HASH 256
#define SIZE_PASSWORD 4
/* Get the hash from a passwod and put the result in hash. The array hash shoud have at lest 14 elements. */
void calculate_hash_password(const char *password, char *hash);
void increment_password(char *password);
void test_password(const char *p_hash, const char *password);
int main(int argc, char *argv[]) {
int i;
char password[SIZE_PASSWORD + 1];
if (argc != 2) {
printf("Use: %s <hash>", argv[0]);
return 1;
}
for (i = 0; i < SIZE_PASSWORD; i++) {
password[i] = 'a';
}
password[SIZE_PASSWORD] = '\0';
while (1) {
test_password(argv[1], password);
increment_password(password);
}
return 0;
}
void test_password(const char *p_hash, const char *password) {
char hash_calculado[SIZE_HASH + 1];
calculate_hash_password(password, hash_calculado);
if (!strcmp(p_hash, hash_calculado)) {
printf("Achou! %s\n", password);
exit(0);
}
}
void increment_password(char *password) {
int i;
i = SIZE_PASSWORD - 1;
while (i >= 0) {
if (password[i] != 'z') {
password[i]++;
i = -2;
} else {
password[i] = 'a';
i--;
}
}
if (i == -1) {
printf("Não achou!\n");
exit(1);
}
}
void calculate_hash_password(const char *password, char *hash) {
struct crypt_data data;
data.initialized = 0;
strcpy(hash, crypt_r(password, "aa", &data));
}
我必须做同样的事情,因为这一个,但使用C中的线程。 我该怎么做?
编辑
答
使用线程来散列密码不是一个特别直观或明显有用的方法,所以它不清楚为什么任何人都想这样做。
据推测为散列计算以某种方式被分离:也许一个线程通过M
处理具有A
开始密码和另一个不N
通过Z
,或一些这样的分区。一个想法是用一个决定执行哪个分区的参数多次运行同一个函数。这是一个简单的,功能正常的程序,它演示了框架。
#include <iostream>
#include <pthread.h>
static void *calc_func (void *arg)
{
int param = (int) arg;
if (param == 1)
{
// do first partition of calculation
// ...
std::cout << "partition 1" << std::endl;
}
else
{
// do second partition of calculation
// ...
std::cout << "partition 2" << std::endl;
}
}
int main (...)
{
// ...
pthread_t threadh[2];
if (pthread_create (&threadh[0], NULL, calc_func, (void *)1) != 0)
{
std::cerr << "error creating thread 1" << std::endl;
}
if (pthread_create (&threadh[1], NULL, calc_func, (void *)2) != 0)
{
std::cerr << "error creating thread 2" << std::endl;
}
// wait for threads to exit
pthread_join (threadh[0], NULL);
pthread_join (threadh[1], NULL);
return 0;
}
要使用gcc构建在Linux上,用我使用的Fedora命令g++ -pthread filename.c++ -o filename
答
在Linux shell中执行:
man pthread_create
请仔细阅读,并提供了一个十分生动的例子,对如何使用线程通知。另请参阅中的功能手册页,另请参阅部分。
如果您使用的是Windows,你可以看到并行线程-win32的here
的之后,你必须决定你的代码的哪一部分(S)的decomentation可以并行化和代码分配给不同的线程。
+0
,我将在你的建议 –
看看我尝试编译你的代码,但给出了一个错误。我用它的图像更新我的帖子,以便您可以看到它。 –
我解决了编译错误更改(int)arg到(long)arg,如下所示:http://stackoverflow.com/questions/1640423/error-cast-from-void-to-int-loses-precision –
@Valter Henrique:这是一个奇怪的错误。尝试将该行中的“int”更改为“long”(或者“long long”)以找到兼容的大小。 – wallyk