查找SQL Server死锁原因

时间:2016-03-14 17:01:49

标签: c++ sql-server multithreading stored-procedures

我有一个在MSVC上运行的简单c ++程序,它使用ODBC连接来执行存储过程。

在主线程上运行它时工作正常,但当我尝试多线程同一个类时,我收到此错误:

  

(进程ID XX)在锁定资源上死锁....

如上所述,我可以在主线程上运行它,也可以在两个线程上运行它没有问题。

这是我如何产生,使用和加入线程:

historical apple("AAPL");
historical google("GOOG");
historical yahoo("YHOO");
historical samsung("005930.KS");
historical ibm("IBM");
auto t1 = thread([&] {apple.go(); });
auto t2 = thread([&] {google.go(); });
auto t3 = thread([&] {yahoo.go(); });
auto t4 = thread([&] {samsung.go(); });
auto t5 = thread([&] {ibm.go(); });

//writer(his.getHistorical()); // this writes to the file test.csv
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();

我知道它看起来很糟糕,但我基本上试图看看在推出软件看起来很漂亮和格式化之前我有多努力。

这就是我调用存储过程的方式:

#include "stdafx.h"
#include "database_con.h"

////////////////////////////////////////////////////////////////////////
// Show errors from the SQLHANDLE

void database_con::show_error(unsigned int handletype, const SQLHANDLE& handle)
{
    SQLWCHAR sqlstate[1024];
    SQLWCHAR message[1024];
    if (SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
        wcout << "Message: " << message << "\nSQLSTATE: " << sqlstate << endl;
}


////////////////////////////////////////////////////////////////////////
// Builds the stored procedure query.

std::wstring database_con::buildQuery(vector<std::wstring> input, string symbol)
{
    std::wstringstream builder;
    builder << L"EXEC sp_addHistorical " << "@Symbol='" << L"" << StringToWString(symbol) << "'," <<
        "@Date='" << (wstring)L"" << input.at(0) << "'," <<
        "@Open=" << (wstring)L"" << input.at(1) << "," <<
        "@Close=" << (wstring)L"" << input.at(2) << "," <<
        "@MaxPrice=" << (wstring)L"" << input.at(3) << "," <<
        "@MinPrice=" << (wstring)L"" << input.at(4) << "," <<
        "@Volume=" << (wstring)L"" << input.at(5) << ";";
    return builder.str();
}

////////////////////////////////////////////////////////////////////////
// Adds a substring of the string before the delimiter to a vector<wstring> that is returned.

std::vector<wstring> database_con::parseData(wstring line, char delim) {
    size_t pos = 0;
    std::vector<std::wstring> vOut;
    while ((pos = line.find(delim)) != std::string::npos) {
        vOut.push_back(line.substr(0, pos));
        line.erase(0, pos + 1);
    }
    vOut.push_back(line.substr(0, pos));
    return vOut;
}
////////////////////////////////////////////////////////////////////////
// Converts a std::string to a std::wstring

std::wstring database_con::StringToWString(const std::string& s)
{
    std::wstring temp(s.length(), L' ');
    std::copy(s.begin(), s.end(), temp.begin());
    return temp;
}
void database_con::historicalLooper(string historical) {

}
////////////////////////////////////////////////////////////////////////
// Constructs a database connector object with the historical data and its symbol

database_con::database_con(std::string historical, string symbol){
    /*
    Set up the handlers
    */

    /* Allocate an environment handle */
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
    /* We want ODBC 3 support */
    SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
    /* Allocate a connection handle */
    SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);

    /* Connect to the DSN */
    SQLDriverConnectW(dbc, NULL, L"DRIVER={SQL Server};SERVER=ERA-PC-STUART\\JBK_DB;DATABASE=master;UID=geo;PWD=kalle123;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
    /* Check for success */
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt))
    {
        show_error(SQL_HANDLE_DBC, dbc);
        std::cout << "Failed to connect";
    }
    _mSymbol = symbol;
    std::wstringstream stream(StringToWString(historical));
    std::wstring line;
    int row = 0;
    while (std::getline(stream, line)) {
        if (row > 0) {
            vector<wstring> vHistorical = parseData(L"" + line, ',');
            std::wstring SQL = buildQuery(vHistorical, _mSymbol);

            if (SQL_SUCCESS != SQLExecDirectW(stmt, const_cast<SQLWCHAR*>(SQL.c_str()), SQL_NTS)) {
                std::cout << "Execute error " << std::endl;
                show_error(SQL_HANDLE_STMT, stmt);
                std::wcout << L"Unsuccessful Query: " << SQL << std::endl;
            }
            // Close Cursor before next iteration starts:
            SQLRETURN closeCursRet = SQLFreeStmt(stmt, SQL_CLOSE);
            if (!SQL_SUCCEEDED(closeCursRet))
            {
                show_error(SQL_HANDLE_STMT, stmt);
                // maybe add some handling for the case that closing failed.
            }
        }
        row++;
    }
    std::cout << "Query " << _mSymbol << " ready" << std::endl;

}

database_con::~database_con() {

}

最后这是存储过程:

GO
CREATE PROCEDURE sp_addHistorical
    @Symbol nchar(10),@Date datetime,
    @Open decimal(12,2),@Close decimal(12,2),@MinPrice decimal(12,2),
    @MaxPrice decimal(12,2),@Volume int
AS 
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    BEGIN TRANSACTION
    MERGE HistoricalStock WITH (UPDLOCK) AS myTarget
        USING (SELECT @Symbol AS Symbol,
        @Date AS Date, @Open AS [Open], @Close AS [Close],
        @MinPrice AS MinPrice, @MaxPrice AS MaxPrice,@Volume AS Volume) AS mySource
        ON mySource.Symbol = myTarget.Symbol AND mySource.Date = myTarget.Date
        WHEN MATCHED 
            THEN UPDATE 
                SET [Open] = mySource.[Open], [Close] = mySource.[Close],
                MinPrice = mySource.MinPrice, MaxPrice = mySource.MaxPrice, Volume = mySource.Volume            
        WHEN NOT MATCHED
            THEN
                INSERT(Symbol,Date,[Open],[Close],MinPrice,MaxPrice,Volume)
                VALUES(@Symbol,@Date,@Open,@Close,@MinPrice,@MaxPrice,@Volume);
    COMMIT 
GO

对于我所面临的问题的所有结构或指示如何提出任何形式的帮助或建议将不胜感激。

我对SQL服务器有点新鲜(更重要的是对存储过程)并且无法确定错误,即使我了解死锁是什么。

谢谢!

0 个答案:

没有答案